diff --git a/README.md b/README.md index cb8f5ed..c87020d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1132 TILs and counting..._ +_1133 TILs and counting..._ --- @@ -746,6 +746,7 @@ _1132 TILs and counting..._ - [Specify New Attributes For #find_or_create_by](rails/specify-new-attributes-for-find-or-create-by.md) - [Temporarily Disable strong_params](rails/temporarily-disable-strong-params.md) - [Test If An Instance Variable Was Assigned](rails/test-if-an-instance-variable-was-assigned.md) +- [Test If deliver_later Is Called For A Mailer](rails/test-if-deliver-later-is-called-for-a-mailer.md) - [Truncate Almost All Tables](rails/truncate-almost-all-tables.md) - [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md) - [Upgrading Your Manifest For Sprocket's 4](rails/upgrading-your-manifest-for-sprockets-4.md) diff --git a/rails/test-if-deliver-later-is-called-for-a-mailer.md b/rails/test-if-deliver-later-is-called-for-a-mailer.md new file mode 100644 index 0000000..e670782 --- /dev/null +++ b/rails/test-if-deliver-later-is-called-for-a-mailer.md @@ -0,0 +1,40 @@ +# Test If deliver_later Is Called For A Mailer + +There are many ways to test in your controller whether emails are going out. A +concise and quick way to check is just to see if a `deliver_later` happened. + +Depending on how your test environment is configured, this could look one of +two ways. + +If you have your `queue_adapter` set to +[`:inline`](https://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/InlineAdapter.html), +then a `deliver_later` will happen synchronously. So, the email will +immediately end up in the `deliveries` box. + +```ruby +expect { + post :password_reset, params: valid_params +}.to change { ActionMailer::Base.deliveries.count }.by(1) +``` + +The behavior is a bit different if your `queue_adapter` is set to something +like +[`:test`](https://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/TestAdapter.html). +In this case, the email is going to be queued in the app's job queue. Since it +is not immediately being sent, the expectation will have to be about the job +queue instead. + +```ruby +expect { + post :password_reset, params: valid_params +}.to have_enqueued_job(ActionMailer::DeliveryJob) +``` + +We can even dig into more specifics like this: + +```ruby +expect { + post :password_reset, params: valid_params +}.to have_enqueued_job(ActionMailer::DeliveryJob) + .with('UserMailer', 'password_reset', 'deliver_later', Integer) +```