Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: Avoid using allow any instance of to receive

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)

like image 576
Maria N Avatar asked Oct 18 '17 15:10

Maria N


1 Answers

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
like image 77
eudaimonia Avatar answered Oct 20 '22 02:10

eudaimonia