【发布时间】:2011-06-11 23:11:39
【问题描述】:
在我的 ApplicationController 中,我有一个定义为辅助方法的方法:
helper_method :some_method_here
- 如何在 RSpec 中测试 ApplicationController?
- 在测试我的视图/帮助器时如何包含/调用此帮助器方法?
我正在使用带有 RSpec2 的 Rails3
【问题讨论】:
标签: ruby-on-rails rspec helper rspec2
在我的 ApplicationController 中,我有一个定义为辅助方法的方法:
helper_method :some_method_here
我正在使用带有 RSpec2 的 Rails3
【问题讨论】:
标签: ruby-on-rails rspec helper rspec2
您可以使用 anonymous controller 来测试您的 ApplicationController,如 RSpec 文档中所述。还有一个关于testing helpers的部分。
【讨论】:
No route matches {:controller=>"anonymous", :action => "some action"}..的问题。
allow(controller).to receive(:any_non_relevant_method_name).and_return(true) 为每个单独的测试删除了不相关的方法,我以 DRY 的方式进行了此操作。
您可以在规范中调用 subject 或 @controller 上的辅助方法。
我一直在寻找解决这个问题的方法,而匿名控制器并不是我想要的。假设您有一个住在app/controllers/application_controller.rb 的控制器,它使用了一个未绑定到 REST 路径的简单方法:
class ApplicationController < ActionController:Base
def your_helper_method
return 'a_helpful_string'
end
end
然后您可以在spec/controllers/application_controller_spec.rb 中编写您的测试,如下所示:
require 'spec_helper'
describe ApplicationController do
describe "#your_helper_method" do
it "returns a helpful string" do
expect(subject.your_helper_method).to eq("a_helpful_string")
end
end
end
虽然@controller 和subject 可以在这里互换使用,但我现在会选择subject 作为它的RSpec 惯用方式。
【讨论】:
current_user helper,它工作正常
helper_method 参数的方法也是如此。我更喜欢将辅助方法定义为protected,然后指定expect(subject.send(:your_helper_method)).to eq "a_helpful_string"。