RSpec: Avoid using allow any instance of to receive

Maria N picture Maria N · Oct 18, 2017 · Viewed 8.8k times · Source

I'm working on one old part of code.

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

There is Rubocop error like:

Avoid stubbing using 'allow_any_instance_of'

I read about RuboCop::RSpec:AnyInstance and I tried to change it like bellow.

From this

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

To this:

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

And with full context: - before

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

... - after:

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

But this doesn't pass the test with error:

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

Answer

eudaimonia picture eudaimonia · Oct 19, 2017

The solution was almost done. You probably need to add build :sport_rate before create

Sth like that

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