Search code examples
ruby-on-railsrubyrspecrspec-railsrails-activejob

Test the number of emails enqueued?


We can check enqueued_jobs.length, provided that email is the only possible type of background job.

it 'sends exactly one, particular email' do
  expect { post :create }.to(
    # First, we can check about the particular email we care about.
    have_enqueued_mail(MyMailer, :my_particular_email)
  )

  # But we also have to check that no other email was sent.
  expect(ActiveJob::Base.queue_adapter.enqueued_jobs.length).to eq(1)
end

Is there a better way to assert that:

  1. MyMailer.my_particular_email was enqueued,
  2. no other email was enqueued,
  3. and we don't care if other, non-email background jobs were enqueued

Solution

  • # first filter MyMailer job 
    my_mail_jobs = ActiveJob::Base.queue_adapter.enqueued_jobs.select { |job|
      job[:job] == SendEmailsJob &&
      job[:args][0] == "MyMailer"
    }
    # check only once
    expect(my_mail_jobs.length).to eq(1) 
    # and that send to your particular email not other email
    expect(my_mail_jobs.first[:args]).to include("your particular email")