instance method assert_enqueued_with

Ruby on Rails 6.0.6

Since v4.2.9

Available in: v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil)

Asserts that the job has been enqueued with the given arguments.

def test_assert_enqueued_with
  MyJob.perform_later(1,2,3)
  assert_enqueued_with(job: MyJob, args: [1,2,3], queue: 'low')

  MyJob.set(wait_until: Date.tomorrow.noon).perform_later
  assert_enqueued_with(job: MyJob, at: Date.tomorrow.noon)
end

The at and args arguments also accept a proc.

To the at proc, it will get passed the actual job’s at argument.

def test_assert_enqueued_with
  expected_time = ->(at) do
    (Date.yesterday..Date.tomorrow).cover?(at)
  end

  MyJob.set(at: Date.today.noon).perform_later
  assert_enqueued_with(job: MyJob, at: expected_time)
end

To the args proc, it will get passed the actual job’s arguments Your proc needs to return a boolean value determining if the job’s arguments matches your expectation. This is useful to check only for a subset of arguments.

def test_assert_enqueued_with
  expected_args = ->(job_args) do
    assert job_args.first.key?(:foo)
  end

  MyJob.perform_later(foo: 'bar', other_arg: 'No need to check in the test')
  assert_enqueued_with(job: MyJob, args: expected_args, queue: 'low')
end

If a block is passed, asserts that the block will cause the job to be enqueued with the given arguments.

def test_assert_enqueued_with
  assert_enqueued_with(job: MyJob, args: [1,2,3], queue: 'low') do
    MyJob.perform_later(1,2,3)
  end

  assert_enqueued_with(job: MyJob, at: Date.tomorrow.noon) do
    MyJob.set(wait_until: Date.tomorrow.noon).perform_later
  end
end

Parameters

job key = nil
args key = nil
at key = nil
queue key = nil
Source
# File activejob/lib/active_job/test_helper.rb, line 393
    def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil)
      expected = { job: job, args: args, at: at, queue: queue }.compact
      expected_args = prepare_args_for_assertion(expected)

      if block_given?
        original_enqueued_jobs_count = enqueued_jobs.count

        yield

        jobs = enqueued_jobs.drop(original_enqueued_jobs_count)
      else
        jobs = enqueued_jobs
      end

      matching_job = jobs.find do |enqueued_job|
        deserialized_job = deserialize_args_for_assertion(enqueued_job)

        expected_args.all? do |key, value|
          if value.respond_to?(:call)
            value.call(deserialized_job[key])
          else
            value == deserialized_job[key]
          end
        end
      end

      assert matching_job, "No enqueued job found with #{expected}"
      instantiate_job(matching_job)
    end

Defined in activejob/lib/active_job/test_helper.rb line 393 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveJob::TestHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close