user10346789
user10346789

Reputation:

RSpec/AnyInstance: Avoid stubbing using allow_any_instance_of problem

Help me. I don't understand how to fix it. I tried to many variations...

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

Error: RSpec/AnyInstance: Avoid stubbing using allow_any_instance_of. before { allow_any_instance_of(described_class).to receive(:driver_iq_api).and_return('https://test/error') }

Upvotes: 8

Views: 11474

Answers (1)

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

You have a pretty specific instance of your described_class that you can stub:

context 'when exception when status is Error' do
  let(:subject) do
    described_class.new(dot_application, background_check_type, provider_setting)
  end
  
  before do
    allow(subject).to receive(:driver_iq_api).and_return('https://test/error')
  end

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

Assuming perform raises the error, not initializing the instance.

Upvotes: 11

Related Questions