`allow_any_instance_of` mock在范围内不起作用

cdp*_*mer 6 ruby rspec ruby-on-rails

我的模拟仅在下面显示的前一个块中工作.这只是我对问题的快速而肮脏的表现.字面上,当我从前一个块移动线到does not quack断言时,它停止嘲笑:(

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
Run Code Online (Sandbox Code Playgroud)

我想在这里,但它不起作用:

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
Run Code Online (Sandbox Code Playgroud)

cdp*_*mer 7

我的错.最初的问题写得不好.访问该页面是#quack调用的原因.在你做任何与方法调用有关的事情之前,必须始终完成模拟.所以这是我的解决方案

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
Run Code Online (Sandbox Code Playgroud)

  • 哇,我想你已经完全解决了我对allow_any_instance_of间歇性成功的困惑。 (2认同)