RSpec: Avoid using allow any instance of to receive

11,873

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
Share:
11,873
Maria N
Author by

Maria N

Updated on June 17, 2022

Comments

  • Maria N
    Maria N about 2 years

    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)