How to test ActionMailer deliver_later with rspec

Using ActiveJob and rspec-rails 3.4+, you could use have_enqueued_job like this:

expect { 
  YourMailer.your_method.deliver_later 
  # or any other method that eventually would trigger mail enqueuing
}.to( 
  have_enqueued_job.on_queue('mailers').with(
    # `with` isn't mandatory, but it will help if you want to make sure is
    # the correct enqueued mail.
    'YourMailer', 'your_method', 'deliver_now', any_param_you_want_to_check
  )
)

also double check in config/environments/test.rb you have:

config.action_mailer.delivery_method = :test
config.active_job.queue_adapter = :test

Another option would be to run inline jobs:

config.active_job.queue_adapter = :inline

But keep in mind this would affect the overall performance of your test suite, as all your jobs will run as soon as they're enqueued.


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.