在Rails 4控制器中使用时,处理关注点测试的最佳方法是什么?说我有个小问题Citations
。
module Citations
extend ActiveSupport::Concern
def citations ; end
end
测试中的预期行为是,任何包含此问题的控制器都将获得此citations
端点。
class ConversationController < ActionController::Base
include Citations
end
简单。
ConversationController.new.respond_to? :yelling #=> true
但是,隔离测试此问题的正确方法是什么?
class CitationConcernController < ActionController::Base
include Citations
end
describe CitationConcernController, type: :controller do
it 'should add the citations endpoint' do
get :citations
expect(response).to be_successful
end
end
不幸的是,这失败了。
CitationConcernController
should add the citations endpoint (FAILED - 1)
Failures:
1) CitationConcernController should add the citations endpoint
Failure/Error: get :citations
ActionController::UrlGenerationError:
No route matches {:controller=>"citation_concern", :action=>"citations"}
# ./controller_concern_spec.rb:14:in `block (2 levels) in <top (required)>'
这是一个人为的例子。在我的应用中,出现了另一个错误。
RuntimeError:
@routes is nil: make sure you set it in your test's setup method.
您会发现许多建议,告诉您使用共享的示例并在包含的控制器范围内运行它们。
我个人认为它过分杀了,宁愿单独进行单元测试,然后使用集成测试来确认控制器的行为。
方法1:没有路由或响应测试
创建一个假控制器并测试其方法:
describe MyControllerConcern do
before do
class FakesController < ApplicationController
include MyControllerConcern
end
end
after do
Object.send :remove_const, :FakesController
end
let(:object) { FakesController.new }
it 'my_method_to_test' do
expect(object).to eq('expected result')
end
end
方法2:测试响应
当您的关注点包含路由或您需要测试响应,渲染等...时,您需要使用匿名控制器运行测试。这使您可以访问所有与控制器相关的rspec方法和帮助器:
describe MyControllerConcern, type: :controller do
controller(ApplicationController) do
include MyControllerConcern
def fake_action; redirect_to '/an_url'; end
end
before do
routes.draw {
get 'fake_action' => 'anonymous#fake_action'
}
end
describe 'my_method_to_test' do
before do
get :fake_action
end
it do
expect(response).to redirect_to('/an_url')
end
end
end
如您所见,我们使用定义了匿名控制器controller(ApplicationController)
。如果您的测试涉及以外的其他课程ApplicationController
,则需要对此进行调整。
另外,要使此方法正常运行,还必须在spec_helper.rb文件中配置以下内容:
config.infer_base_class_for_anonymous_controllers = true
注意:请继续测试是否包含您的担忧
测试您的关注类别是否包含在目标类别中也很重要,只需一行即可:
describe SomeTargetedController do
it 'includes MyControllerConcern' do
expect(SomeTargetedController.ancestors.include? MyControllerConcern).to be(true)
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句