Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect multiple Rails Active Jobs of the same class to be enqueued with different parameters

I have a Rails Active Job that creates multiple other jobs of the same type with different parameters. I want to test that this job enqueues the other job with the correct parameters.

This is basically what I'm trying to achieve:

require 'rails_helper'

RSpec.describe TriggerJob, type: :job do
  include ActiveJob::TestHelper

  after do
    clear_enqueued_jobs
  end

  it 'enqueues jobs for all model instances' do
    model1 = create(:model)
    model2 = create(:model)
    model3 = create(:model)

    expect { described_class.perform_now }
      .to(have_enqueued_job(ModelJob).with { |arg| expect(arg.id).to be == model1.id }.exactly(:once))
      .and(have_enqueued_job(ModelJob).with { |arg| expect(arg.id).to be == model2.id }.exactly(:once))
      .and(have_enqueued_job(ModelJob).with { |arg| expect(arg.id).to be == model3.id }.exactly(:once))
  end
end

This does not work because RSpec seems to simply match the job class type and then tries to compare the first jobs arguments with my block. Depending on the order in the queue, this fails. I'd like RSpec to match ANY of the enqueued ModelJob jobs and only fail if it can't find any match in the queue.

Additionally I'd like to test that no other ModelJob jobs exist with different parameters, but this is not really required.

like image 864
Strayer Avatar asked Apr 28 '20 09:04

Strayer


Video Answer


1 Answers

# ...
it 'schedules the job with different arguments' do
    described_class.perform_now

    expect(ModelJob).to(have_been_enqueued.at_least(:once).with(model1.id))

    expect(ModelJob).to(have_been_enqueued.at_least(:once).with(model2.id))

    expect(ModelJob).to(have_been_enqueued.at_least(:once).with(model3.id))
end
like image 166
Sadjow Avatar answered Oct 14 '22 04:10

Sadjow