为sidekiq工作者编写测试

时间:2013-09-12 02:04:12

标签: rspec rspec-rails sidekiq rspec-sidekiq

我正在使用rspec-sidekiq gem(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上的示例,但它对我不起作用...为什么这不起作用的任何原因?

2 个答案:

答案 0 :(得分:26)

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

您可以通过实例化作业类并调用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

答案 1 :(得分:2)

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

查看:https://github.com/mperham/sidekiq/wiki/Testing了解详情。

相关问题