Search code examples
ruby-on-railsrubyrspecworker

How to build a spec for a waiting worker


I am trying to make a spec for this call (kind of simple job):

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

The spec that I currently have:

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

And it works fine, but I also want to test that it is calling perform_later after 3 seconds. What is the right way to do that?

Thank you!


Solution

  • You can use ActiveJob::TestHelper and ActiveSupport::Testing::TimeHelpers.

    Add helper to rails_helper.rb.

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

    Add test to spec.

    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