我正在尝试在我的控制器中定义的助手上存根方法。例如:
class ApplicationController < ActionController::Base
def current_user
@current_user ||= authenticated_user_method
end
helper_method :current_user
end
module SomeHelper
def do_something
current_user.call_a_method
end
end
在我的 Rspec 中:
describe SomeHelper
it "why cant i stub a helper method?!" do
helper.stub!(:current_user).and_return(@user)
helper.respond_to?(:current_user).should be_true # Fails
helper.do_something # Fails 'no method current_user'
end
end
在spec/support/authentication.rb
module RspecAuthentication
def sign_in(user)
controller.stub!(:current_user).and_return(user)
controller.stub!(:authenticate!).and_return(true)
helper.stub(:current_user).and_return(user) if respond_to?(:helper)
end
end
RSpec.configure do |config|
config.include RspecAuthentication, :type => :controller
config.include RspecAuthentication, :type => :view
config.include RspecAuthentication, :type => :helper
end
我在这里问了一个类似的问题,但解决了一个问题。这种奇怪的行为再次蔓延,我想了解为什么这不起作用。
更新:我发现controller.stub!(:current_user).and_return(@user)
之前调用helper.stub!(...)
是导致这种行为的原因。这很容易修复spec/support/authentication.rb
,但这是 Rspec 中的错误吗?如果它已经在控制器上存根,我不明白为什么它不能在助手上存根方法。