如何为等待的工人建立规范

时间:2019-02-08 22:51:17

标签: ruby-on-rails ruby rspec worker

我正在为此电话(一种简单的工作)制定规格:

SomeJob.set(wait: 3.seconds).perform_later(messenger.id, EVENT)

我当前拥有的规格:

it 'should call an event for...' do
  expect(SomeJob).to receive(:set).with(wait: 3.seconds).and_call_original
  subject.save
end

它工作正常,但我还想测试3秒钟后它正在调用perform_later。正确的方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用ActiveJob::TestHelperActiveSupport::Testing::TimeHelpers

将帮助程序添加到rails_helper.rb

  config.include ActiveJob::TestHelper
  config.include ActiveSupport::Testing::TimeHelpers

将测试添加到规范中。

class Some < ApplicationRecord
  def hello
    SomeJob.set(wait: 3.seconds).perform_later 'Hello!'
  end
end
RSpec.describe Some, type: :model do
  it 'should start job after 3 seconds' do
    time = Time.current
    travel_to(time) do
      assertion = {
        job: SomeJob,
        args: ['Hello!'],
        at: (time + 3.seconds).to_i
      }
      assert_enqueued_with(assertion) { Some.new.hello }
    end
  end
end