我在 ApplicationController 中定义了一个方法作为帮助方法:
helper_method :some_method_here
- 如何在 RSpec 中测试 ApplicationController ?
- 如何在测试我的视图/帮助程序时包含 / 调用此帮助方法?
我正在使用 Rails3 和 RSpec2。
我在 ApplicationController 中定义了一个方法作为帮助方法:
helper_method :some_method_here
我正在使用 Rails3 和 RSpec2。
您可以在规范中使用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
еҠ©жүӢпјҢе®ғжӯЈеёёиҝҗиЎҢгҖӮ - Nícolas Iensenhelper_method
参数的方法也是如此。我更喜欢将辅助方法定义为“protected”,然后使用expect(subject.send(:your_helper_method)).to eq "a_helpful_string"
进行规范化。 - Epigene
allow(controller).to receive(:any_non_relevant_method_name).and_return(true)
为每个单独的测试挑选出非相关的方法。我以DRY的方式完成了这个过程。 - ryan2johnson9