gpt4 book ai didi

ruby-on-rails - 无法使用 rspec stub 辅助方法

转载 作者:行者123 更新时间:2023-12-03 01:15:28 25 4
gpt4 key购买 nike

我正在尝试在我的 Controller 中定义的帮助器上 stub 一个方法。例如:

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

我问了类似的问题here ,但决定采取解决办法。这种奇怪的行为再次出现,我想了解为什么这不起作用。

更新:我发现在 helper.stub!(... ) 是导致此行为的原因。这很容易在 spec/support/authentication.rb 中修复,但这是 Rspec 中的错误吗?我不明白为什么如果已经在 Controller 上 stub 了方法,就无法在助手上 stub 方法。

最佳答案

更新 Matthew Ratzloff 的答案:您不需要实例对象和 stub !已被弃用

it "why can't I stub a helper method?!" do
helper.stub(:current_user) { user }
expect(helper.do_something).to eq 'something'
end

编辑。 RSpec 3 的 stub! 方法是:

allow(helper).to receive(:current_user) { user }

参见:https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/

关于ruby-on-rails - 无法使用 rspec stub 辅助方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10537932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com