为sidekiq工作者编写测试

den*_*icz 21 rspec rspec-rails sidekiq rspec-sidekiq

我正在使用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
Run Code Online (Sandbox Code Playgroud)

这是错误:

 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)>'
Run Code Online (Sandbox Code Playgroud)

我将他们的低级别测试基于他们的维基上的示例,但它不适合我...任何理由为什么这不起作用?

Win*_*eld 30

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

您可以通过实例化作业类和调用来测试作业的执行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
Run Code Online (Sandbox Code Playgroud)

但是,这实际上只是测试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
Run Code Online (Sandbox Code Playgroud)

  • 在给出这个答案时,我猜测'have_enqueued_jobs`仍然有效,但现在正确的语法是`have(1).jobs` (2认同)