首页 > 解决方案 > 如何为等待的工人建立规范

问题描述

我正在尝试为此调用制定规范(一种简单的工作):

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

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

谢谢!

标签: ruby-on-railsrubyrspecworker

解决方案


您可以使用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

推荐阅读