22

我正在使用rspec-sidekiqgem ( https://github.com/philostler/rspec-sidekiq ) 来帮助测试我正在编写的工人,但由于某种原因,我的测试一直失败。

这是我的测试:

require 'spec_helper'

describe CommunicationWorker do
  it { should be_retryable false }

  it "enqueues a communication worker" do
    subject.perform("foo@bar.com", "bar@foo.com", [1,2,3])
    expect(CommunicationWorker).to have_enqueued_jobs(1)
  end
end

这是错误:

 1) CommunicationWorker enqueues a communication worker
     Failure/Error: expect(CommunicationWorker).to have_enqueued_jobs(1)
       expected CommunicationWorker to have 1 enqueued job but got 0
     # ./spec/workers/communication_worker_spec.rb:9:in `block (2 levels) in <top (required)>'

我在他们的 wiki 上基于他们的示例进行了低级测试,但它对我不起作用……有什么理由不起作用?

4

2 回答 2

32

这里有两件事要测试,队列中作业的异步入队和作业的执行。

您可以通过实例化作业类并调用perform().

您可以通过调用perform_async()作业类来测试作业的排队。

要测试测试中的期望,您应该执行以下操作:

 it "enqueues a communication worker" do
    CommunicationWorker.perform_async("foo@bar.com", "bar@foo.com", [1,2,3])
    expect(CommunicationWorker).to have(1).jobs
  end

然而,这实际上只是测试 Sidekiq 框架,并不是一个有用的测试。我建议为工作本身的内部行为编写测试:

 it "enqueues a communication worker" do
    Widget.expects(:do_work).with(:some_value)
    Mailer.expects(:deliver)

    CommunicationWorker.new.perform("foo@bar.com", "bar@foo.com", [1,2,3])
  end
于 2013-09-13T18:12:41.357 回答
2

测试方法是什么?尝试用Sidekiq::Testing.fake! do <your code> end. 这将确保使用假队列。如果 sidekiq 的测试方法是“内联”的,worker 将立即执行(因此您的队列长度为 0)。

查看:https ://github.com/mperham/sidekiq/wiki/Testing了解更多信息。

于 2013-12-16T13:40:32.677 回答