Skip to content

Commit 18cf502

Browse files
committed
Add Test If deliver_later Is Called For A Mailer as a rails til
1 parent 1de308f commit 18cf502

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1132 TILs and counting..._
13+
_1133 TILs and counting..._
1414

1515
---
1616

@@ -746,6 +746,7 @@ _1132 TILs and counting..._
746746
- [Specify New Attributes For #find_or_create_by](rails/specify-new-attributes-for-find-or-create-by.md)
747747
- [Temporarily Disable strong_params](rails/temporarily-disable-strong-params.md)
748748
- [Test If An Instance Variable Was Assigned](rails/test-if-an-instance-variable-was-assigned.md)
749+
- [Test If deliver_later Is Called For A Mailer](rails/test-if-deliver-later-is-called-for-a-mailer.md)
749750
- [Truncate Almost All Tables](rails/truncate-almost-all-tables.md)
750751
- [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md)
751752
- [Upgrading Your Manifest For Sprocket's 4](rails/upgrading-your-manifest-for-sprockets-4.md)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)