RSpec / AnyInstance:避免使用allow_any_instance_of问题进行存根

时间:2018-11-15 13:41:49

标签: ruby-on-rails ruby rspec

帮帮我。我不知道该如何解决。我尝试了很多变化...

driver_iq_driver_spec.rb

describe '.perform' do
it 'correctly parse response' do
  driver = described_class.new(dot_application, background_check_type, provider_setting).perform
  expect(driver).to be_instance_of(BackgroundCheck)
  expect(driver).to have_attributes(status: 'inprogress', background_check_type_id: 4)
end

context 'when exception when status is Error' do
  before { allow_any_instance_of(described_class).to receive(:driver_iq_api).and_return('https://test/error') }

  it 'returns error message' do
    expect { described_class.new(dot_application, background_check_type, provider_setting).perform }.
      to raise_error(RuntimeError)
  end
 end
end
  

错误:RSpec / AnyInstance:避免使用allow_any_instance_of进行存根。         在{allow_any_instance_of(describe_class).to接收(:driver_iq_api).and_return('https://test/error')}

之前

1 个答案:

答案 0 :(得分:1)

您有一个described_class的非常具体的实例可以存根:

context 'when exception when status is Error' do
  let(:subject) { described_class.new(dot_application, background_check_type, provider_setting) }

  before { allow(subject).to receive(:driver_iq_api).and_return('https://test/error') }

  it 'returns error message' do
    expect { subject.perform }.to raise_error(RuntimeError)
  end
 end

假设perform会引发错误,而不是初始化实例。