コントローラで定義されているヘルパーでメソッドをスタブしようとしています。例えば:
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のバグですか?メソッドがすでにコントローラーでスタブされている場合、ヘルパーでメソッドをスタブできないと予想される理由がわかりません。