gpt4 book ai didi

ruby-on-rails - Rspec 如何避免 allow_any_instance_of

转载 作者:行者123 更新时间:2023-12-05 05:07:53 25 4
gpt4 key购买 nike

由于 rubocop 错误,我想避免在我的规范中使用 allow_any_instance_of

我正在尝试改变这个:

  before do
allow_any_instance_of(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
end

it 'returns http success' do
expect(response).to have_http_status(:success)
end

根据rubocop-docs它应该是这样的:

  let(:maintenance_mode?) { instance_double(ApplicationController) }

before do
allow(ApplicationController).to receive(:maintenance_mode_active?).and_return(false)
allow(maintenance_mode?).to receive(:maintenance_mode_active?)
end

it 'returns http success' do
expect(response).to have_http_status(:success)
end

我要测试的类:

private

def check_maintenance?
if maintenance_mode_active? == true
redirect_to maintenance_mode
elsif request.fullpath.include?(maintenance_mode_path)
redirect_to :root
end
end

def maintenance_mode_active?
# do sth ...
mode.active?
end

上面的代码出现错误:

 2.1) Failure/Error: allow(ApplicationController).to receive(maintenance_mode?).and_return(false)
#<InstanceDouble(ApplicationController) (anonymous)> received unexpected message :to_sym with (no args)
# ./spec/controllers/static_pages_controller_spec.rb:15:in `block (4 levels) in <top (required)>'

2.2) Failure/Error: allow(ApplicationController).to receive(maintenance_mode?).and_return(false)

TypeError:
[#<RSpec::Mocks::MockExpectationError: #<InstanceDouble(ApplicationController) (anonymous)> received unexpected message :to_sym with (no args)>] is not a symbol nor a string
# ./spec/controllers/static_pages_controller_spec.rb:15:in `block (4 levels) in <top (required)>'

最佳答案

您必须 stub ApplicationController 以返回 instance_double(ApplicationController):

let(:application_controller) { instance_double(ApplicationController) }

allow(ApplicationController).to receive(:new).and_return(application_controller)
allow(application_controller).to receive(:maintenance_mode_active?).and_return(false)

关于ruby-on-rails - Rspec 如何避免 allow_any_instance_of,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58772889/

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