Search code examples
ruby-on-railsrspecactionmailerdelayed-jobrails-activejob

How to test ActionMailer deliver_later with rspec


trying to upgrade to Rails 4.2, using delayed_job_active_record. I've not set the delayed_job backend for test environment as thought that way jobs would execute straight away.

I'm trying to test the new 'deliver_later' method with RSpec, but I'm not sure how.

Old controller code:

ServiceMailer.delay.new_user(@user)

New controller code:

ServiceMailer.new_user(@user).deliver_later

I USED to test it like so:

expect(ServiceMailer).to receive(:new_user).with(@user).and_return(double("mailer", :deliver => true))

Now I get errors using that. (Double "mailer" received unexpected message :deliver_later with (no args))

Just

expect(ServiceMailer).to receive(:new_user)

fails too with 'undefined method `deliver_later' for nil:NilClass'

I've tried some examples that allow you to see if jobs are enqueued using test_helper in ActiveJob but I haven't managed to test that the correct job is queued.

expect(enqueued_jobs.size).to eq(1)

This passes if the test_helper is included, but it doesn't allow me to check it is the correct email that is being sent.

What I want to do is:

  • test that the correct email is queued (or executed straight away in test env)
  • with the correct parameters (@user)

Any ideas?? thanks


Solution

  • If I understand you correctly, you could do:

    message_delivery = instance_double(ActionMailer::MessageDelivery)
    expect(ServiceMailer).to receive(:new_user).with(@user).and_return(message_delivery)
    allow(message_delivery).to receive(:deliver_later)
    

    The key thing is that you need to somehow provide a double for deliver_later.