ruby-on-rails - 设置 resque .perform 方法的期望。任务在回调中排队

标签 ruby-on-rails rspec resque resque-retry

所以根据我的理解,我相信你这样做

Resque.inline = Rails.env.test?

您的 resque 任务将同步运行。我正在编写一个关于 resque 任务的测试,该任务在 after_commit 回调期间进入队列。

after_commit:enqueue_several_jobs

#class PingsEvent < ActiveRecord::Base
...
   def enqueue_several_jobs
      Resque.enqueue(PingFacebook, self.id)
      Resque.enqueue(PingTwitter, self.id)
      Resque.enqueue(PingPinterest, self.id)
   end

在 Resque 任务类的 .perform 方法中,我正在执行 Rails.logger.info ,在我的测试中,我正在执行类似的操作

..
Rails.logger.should_receive(:info).with("PingFacebook sent with id #{dummy_event.id}")
PingsEvent.create(params)

我对 PingTwitterPingPinterest 进行了相同的测试。

我在第二个和第三个期望上失败了,因为看起来测试实际上在所有 resque 作业运行之前完成。只有第一个测试真正通过了。然后,RSpec 抛出一个 MockExpectationError ,告诉我 Rails.logger 没有收到其他两个测试的 .info 。有人以前有过这方面的经验吗?

编辑

有人提到 should_receive 的行为类似于 mock,而我应该执行 .exactly(n).times 。很抱歉没有早点说清楚,但我对不同的 it block 有自己的期望,并且我不认为在一个 it block 中存在 should_receive会在下一个 it block 中模拟它吗?如果我的说法有误,请告诉我。

最佳答案

class A
  def bar(arg)
  end

  def foo
    bar("baz")
    bar("quux")
  end
end

describe "A" do
  let(:a) { A.new }

  it "Example 1" do
    a.should_receive(:bar).with("baz")
    a.foo # fails 'undefined method bar'
  end
  it "Example 2" do
    a.should_receive(:bar).with("quux")
    a.foo # fails 'received :bar with unexpected arguments
  end
  it "Example 3" do
    a.should_receive(:bar).with("baz")
    a.should_receive(:bar).with("quux")
    a.foo # passes
  end
  it "Example 4" do
    a.should_receive(:bar).with(any_args()).once
    a.should_receive(:bar).with("quux")
    a.foo # passes
  end
end

与 stub 一样,消息期望取代了方法的实现。满足期望后,对象将不再响应方法调用——这会导致“未定义的方法”(如示例 1 所示)。

示例 2 显示了当由于参数不正确而导致期望失败时会发生什么情况。

示例 3 展示了如何对同一方法的多个调用进行 stub ——按照收到的顺序使用正确的参数对每个调用进行 stub 。

示例 4 表明,您可以使用 any_args() 帮助器在一定程度上减少这种耦合。

关于ruby-on-rails - 设置 resque .perform 方法的期望。任务在回调中排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149986/

相关文章:

ruby-on-rails - VCR 正在返回 UnhandledHTTPRequestError

ruby-on-rails - 在验收规范中测试或不测试什么?

ruby-on-rails - heroku 上的多线程 ruby​​ worker

ruby-on-rails-3 - 只测试一个它或用 Rspec 描述

ruby - 如何使用 rspec 测试多线程 TCPServer

ruby-on-rails - 如何在生产中启动一个resque队列(EC2/Ubuntu)?

html - 错误的 URI Ruby on Rails : is it because long?

ruby-on-rails - 如何在 resque 作业中使用 ruby​​-debugger?

ruby-on-rails - 在 Heroku 上使用 Resque 的后台作业

ruby - rspec webmock to_raise 错误未引发错误