无法使用 rspec 存根辅助方法 [英] Unable to stub helper method with rspec

查看:59
本文介绍了无法使用 rspec 存根辅助方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的控制器中定义的帮助程序上存根一个方法.例如:

I am trying to stub a method on a helper that is defined in my controller. For example:

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 中:

In my 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

我在这里问了一个类似的问题,但决定解决.这种奇怪的行为再次出现,我想了解为什么这不起作用.

I asked a similar question here, but settled on a work around. This strange behavior has creeped up again and I would like to understand why this doesnt work.

UPDATE:我发现在 helper.stub!(...) 是导致这种行为的原因.这很容易在 spec/support/authentication.rb 中修复,但这是 Rspec 中的错误吗?我不明白为什么如果它已经在控制器上存根了,为什么它不能存根在助手上的方法.

UPDATE: I have found that calling controller.stub!(:current_user).and_return(@user) before helper.stub!(...) is what is causing this behavior. This is easy enough to fix in spec/support/authentication.rb, but is this a bug in Rspec? I dont see why it would be expected to not be able to stub a method on a helper if it was already stubbed on a controller.

推荐答案

试试这个,它对我有用:

Try this, it worked for me:

describe SomeHelper
  before :each do
    @helper = Object.new.extend SomeHelper
  end

  it "why cant i stub a helper method?!" do
    @helper.stub!(:current_user).and_return(@user)
    # ...
  end
end

第一部分基于此回复RSpec 的作者,第二部分基于 this Stack Overflow answer.

The first part is based on this reply by the author of RSpec, and the second part is based on this Stack Overflow answer.

这篇关于无法使用 rspec 存根辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆