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

时间:2015-06-02 16:59:15

标签: ruby-on-rails ruby rspec

我的模拟仅在下面显示的前一个块中有效。这只是我对问题的快速而肮脏的表现。字面意思是当我将前一行的行移到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

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

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

1 个答案:

答案 0 :(得分: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