Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`allow_any_instance_of` mock not working in scope

My mock is only working when it's in the before block shown below. This is just my quick and dirty representation of my problem. Literally when I move the line from the before block to the does not quack assertion, it stops mocking :(

describe 'Ducks', type: :feature do
  before do
    ...
    allow_any_instance_of(Duck).to receive(:quack).and_return('bark!')
    visit animal_farm_path
  end

  context 'is an odd duck'
    it 'does not quack' do
      expect(Duck.new.quack).to eq('bark!')
    end
  end
end

I want it here, but it doesn't work:

describe 'Ducks', type: :feature do
  before do
    ...
    visit animal_farm_path
  end

  context 'is an odd duck'
    it 'does not quack' do
      allow_any_instance_of(Duck).to receive(:quack).and_return('bark!')
      expect(Duck.new.quack).to eq('bark!')
    end
  end
end
like image 696
cdpalmer Avatar asked Jun 02 '15 16:06

cdpalmer


1 Answers

My bad. The original question was poorly written. Visiting the page is what makes the #quack call. The mocks must always be done before you do whatever it is that engages the method call. So this was my solution

describe 'Ducks', type: :feature do
  before do
    ...
  end

  context 'is an odd duck'
    it 'does not quack' do
      allow_any_instance_of(Duck).to receive(:quack).and_return('bark!')
      visit animal_farm_path

      # In this crude example, the page prints out the animals sound
      expect(page).to have_text('bark!')
    end
  end
end
like image 192
cdpalmer Avatar answered Nov 05 '22 14:11

cdpalmer