ruby-on-rails - `allow_any_instance_of` 模拟不在范围内工作

标签 ruby-on-rails ruby rspec

我的 mock 只有在如下所示的 before block 中时才有效。这只是我对我的问题的快速而肮脏的表述。从字面上看,当我将行从 before block 移动到 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

最佳答案

我的错。原来的问题写得不好。访问该页面是调用 #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

关于ruby-on-rails - `allow_any_instance_of` 模拟不在范围内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30602193/

相关文章:

ruby-on-rails - 为什么我不能用 gem install rails -v 4.0.0 安装 rails?

ruby-on-rails - 存在单引号时 RSpec `match` 失败

javascript - haml/javascript/erb 转义

ruby-on-rails - 如何为 Ruby on Rails 项目创建项目模板?

ruby-on-rails - around_action 回调如何工作?需要解释

ruby - 在 ERB 模板中转义换行符/行尾

ruby-on-rails - 如何在 rspec 测试中设置 HTTP_USER_AGENT

ruby /Rspec : should be_false vs should == false

ruby-on-rails - 使用 FactoryGirl 的序列时验证失败

ruby-on-rails - Heroku 每日自动复制 Postgres 数据库