Skip to content

Commit

Permalink
Gracefully degrade when ActionMailer::Base#params is nil
Browse files Browse the repository at this point in the history
Prior to this change, access to `params` on `ActionMailer::Base`
instances prior to being decorated by `ActionMailer::Parameterized.with`
calls results in a `NoMethodError`:

```
Error:
ParameterizedTest#test_degrade_gracefully_when_.with_is_not_called:
NoMethodError: undefined method `[]' for nil:NilClass

  before_action { @Inviter, @invitee = params[:inviter], params[:invitee] }
                                             ^^^^^^^^^^
```

This change modifies the `attr_accessor :params` to be an `attr_writer`
paired with a `params` method that assigns `@params` to an empty `Hash`
whenever it's accessed without being otherwise initialized.
  • Loading branch information
seanpdoyle committed Jan 21, 2023
1 parent 6bace37 commit 6fea9a0
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
4 changes: 4 additions & 0 deletions actionmailer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Default `ActionMailer::Parameterized#params` to an empty `Hash`

*Sean Doyle*

* `assert_emails` now returns the emails that were sent.

This makes it easier to do further analysis on those emails:
Expand Down
6 changes: 5 additions & 1 deletion actionmailer/lib/action_mailer/parameterized.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,11 @@ module Parameterized
extend ActiveSupport::Concern

included do
attr_accessor :params
attr_writer :params

def params
@params ||= {}
end
end

module ClassMethods
Expand Down
7 changes: 7 additions & 0 deletions actionmailer/test/parameterized_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ class DummyDeliveryJob < ActionMailer::MailDeliveryJob
assert_equal("So says david@basecamp.com", @mail.body.encoded)
end

test "degrade gracefully when .with is not called" do
@mail = ParamsMailer.invitation

assert_nil(@mail.to)
assert_nil(@mail.from)
end

test "enqueue the email with params" do
args = [
"ParamsMailer",
Expand Down

0 comments on commit 6fea9a0

Please sign in to comment.