我如何指定 before_filters? [英] How can I spec before_filters?
本文介绍了我如何指定 before_filters?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用 rspec 指定我的控制器 before_filter.我想为它使用 ActionController::Testing::ClassMethods#before_filters.
I want to spec my controllers before_filter with rspec. I thought to use ActionController::Testing::ClassMethods#before_filters for it.
我在 rails c 中得到了这些结果:
I got these results in my rails c:
2.0.0p353 :006 > ActionController::Base.singleton_class.send :include, ActionController::Testing::ClassMethods
2.0.0p353 :003 > EquipmentController.before_filters
=> [:process_action, :process_action]
=> [:process_action, :process_action]
但实际上这是我操作的过滤器:
But in reality this is the filter on my action:
class EquipmentController < ApplicationController
before_filter :authenticate_user!
有什么想法吗?
推荐答案
这是我在我的项目中所做的:
This is what I did in my project:
# spec/support/matchers/have_filters.rb
RSpec::Matchers.define :have_filters do |kind, *names|
match do |controller|
filters = controller._process_action_callbacks.select{ |f| f.kind == kind }.map(&:filter)
names.all?{ |name| filters.include?(name) }
end
end
# spec/support/controller_macros.rb
module ControllerMacros
def has_before_filters *names
expect(controller).to have_filters(:before, *names)
end
end
# spec/spec_helper.rb
RSpec.configure do |config|
config.include ControllerMacros, type: :controller
end
然后你可以在控制器规范中使用它,例如:
and then you can just use it in controller specs like:
# spec/controllers/application_controller_spec.rb
require 'spec_helper'
describe ApplicationController do
describe 'class' do
it { has_before_filters(:authenticate_user) }
end
end
这篇关于我如何指定 before_filters?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文