|
| 1 | +# Test If deliver_later Is Called For A Mailer |
| 2 | + |
| 3 | +There are many ways to test in your controller whether emails are going out. A |
| 4 | +concise and quick way to check is just to see if a `deliver_later` happened. |
| 5 | + |
| 6 | +Depending on how your test environment is configured, this could look one of |
| 7 | +two ways. |
| 8 | + |
| 9 | +If you have your `queue_adapter` set to |
| 10 | +[`:inline`](https://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/InlineAdapter.html), |
| 11 | +then a `deliver_later` will happen synchronously. So, the email will |
| 12 | +immediately end up in the `deliveries` box. |
| 13 | + |
| 14 | +```ruby |
| 15 | +expect { |
| 16 | + post :password_reset, params: valid_params |
| 17 | +}.to change { ActionMailer::Base.deliveries.count }.by(1) |
| 18 | +``` |
| 19 | + |
| 20 | +The behavior is a bit different if your `queue_adapter` is set to something |
| 21 | +like |
| 22 | +[`:test`](https://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/TestAdapter.html). |
| 23 | +In this case, the email is going to be queued in the app's job queue. Since it |
| 24 | +is not immediately being sent, the expectation will have to be about the job |
| 25 | +queue instead. |
| 26 | + |
| 27 | +```ruby |
| 28 | +expect { |
| 29 | + post :password_reset, params: valid_params |
| 30 | +}.to have_enqueued_job(ActionMailer::DeliveryJob) |
| 31 | +``` |
| 32 | + |
| 33 | +We can even dig into more specifics like this: |
| 34 | + |
| 35 | +```ruby |
| 36 | +expect { |
| 37 | + post :password_reset, params: valid_params |
| 38 | +}.to have_enqueued_job(ActionMailer::DeliveryJob) |
| 39 | + .with('UserMailer', 'password_reset', 'deliver_later', Integer) |
| 40 | +``` |
0 commit comments