【问题标题】:How to ignore some calls to the same method with different argument in Rspec?如何在 Rspec 中忽略对具有不同参数的同一方法的某些调用?
【发布时间】:2023-04-07 16:26:01
【问题描述】:

这是我的场景:

更新 AR 对象后,它会使用 Resque 触发一堆后台作业。在我的规范中,我在嘲笑对 Resque#enqueue 的调用,类似于:

it 'should be published' do
  # I need to setup these mocks in many places where I want to mock a specific call to Resque, otherwise it fails
  Resque.should_receive(:enqueue).with(NotInterestedJob1, anything)
  Resque.should_receive(:enqueue).with(NotInterestedJob2, anything)
  Resque.should_receive(:enqueue).with(NotInterestedJob3, anything)

  # I'm only interested in mocking this Resque call.
  Resque.should_receive(:enqueue).with(PublishJob, anything)
end

如您所见,每次我想模拟特定调用时,我都需要模拟对 Resque#enqueue 的所有其他调用,有没有办法只模拟自定义调用而忽略具有不同参数的其他调用?

提前致谢;)

【问题讨论】:

  • 我认为您已经发布的内容应该可以使用 - 有什么问题?
  • 嗨 Frederick,问题是当我想模拟特定的 Resque 调用时,我需要在每个地方添加所有这些模拟。

标签: ruby-on-rails ruby rspec mocking resque


【解决方案1】:

我认为在这种情况下,您需要执行我认为与 as_null_object 等效的方法存根,但在这种情况下,专门针对您不关心的对 Resque.enqueue 的调用:

it 'should be published' do
  allow(Resque).to receive(:enqueue) # stub out this message entirely
  expect(Resque).to receive(:enqueue).with(PublishJob, anything)
  call_your_method.that_calls_enqueue
end

【讨论】:

  • 感谢您的帮助 Paul,我使用的是 Rspec 2,所以 #allow 和 #receive 不可用,但我已将它们替换为 Resque.stub(:enqueue).and_return(true)Resque.should_receive(:enqueue).with(PublishJob, anything)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 2017-09-06
  • 2013-06-02
相关资源
最近更新 更多