gpt4 book ai didi

ruby-on-rails - RSpec:避免使用允许接收的任何实例

转载 作者:数据小太阳 更新时间:2023-10-29 07:13:19 26 4
gpt4 key购买 nike

我正在处理旧代码的一部分。

before do
allow_any_instance_of(SportRateManager)
.to receive(:create)
.and_return(true)
end

Rubocop 错误如下:

Avoid stubbing using 'allow_any_instance_of'

我读到了 RuboCop::RSpec:AnyInstance我试着像下面那样改变它。

由此

before do
allow_any_instance_of(SportRateManager)
.to receive(:create)
.and_return(true)
end

对此:

let(:sport_manager) { instance_double(SportRateManager) }

before do
allow(SportRateManager).to receive(:new).and_return(sport_manager)
allow(sport_manager).to receive(:create).and_return(true)
end

以及完整的上下文:- 之前

describe 'POST create' do
let(:sport_rate) { build(:sport_rate) }
let(:action) { post :create, sport_rate: sport_rate.attributes }

context 'when sport rate manager created the rate successfully' do
before do
allow_any_instance_of(SportRateManager)
.to receive(:create)
.and_return(true)
end

it 'returns ok status' do
action
expect(response).to have_http_status(:ok)
end
end

... - 之后:

describe 'POST create' do
let(:sport_rate) { build(:sport_rate) }
let(:action) { post :create, sport_rate: sport_rate.attributes }
let(:sport_manager) { instance_double(SportRateManager) }

context 'when sport rate manager created the sport successfully' do
before do
allow(SportRateManager).to receive(:new).and_return(sport_manager)
allow(sport_manager).to receive(:create).and_return(true)
end

it 'returns ok status' do
action
expect(response).to have_http_status(:ok)
end
end

但这并没有通过错误的测试:

#<InstanceDouble(SportRateManager) (anonymous)> received unexpected message :sport_rate with (no args)

最佳答案

解决方案几乎完成了。您可能需要在创建之前添加 build :sport_rate

诸如此类

let(:sport_manager) { instance_double(SportRateManager) }

before do
allow(SportRateManager).to receive(:new).and_return(sport_manager)
allow(sport_manager).to receive(:sport_rate).and_return(build :sport_rate)
allow(sport_manager).to receive(:create).and_return(true)
end

关于ruby-on-rails - RSpec:避免使用允许接收的任何实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46813303/

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