Aaron Renoir
Aaron Renoir

Reputation: 4391

Rails 4 ActionMailer Sending Email With Name not working as expected

I am having trouble testing my mailer. It appears assigning attributes [:to, :from, :reply_to] with a email in the format described as email-with-name doesn't work.

Here is a simple example.

class MessageMailer < ActionMailer::Base
    def simple
      mail(
        from: "Aaron Test <[email protected]>",
        to: "Aaron Test <[email protected]>",
        reply_to: "Aaron Test <[email protected]>"
      )
    end
end

message_mailer_spec.rb

EXPECTED = "Aaron Test <[email protected]>"

describe MessageMailer do
  before do
    @email = MessageMailer.simple
  end

  it "expect `from` to eq #{EXPECTED}" do
    expect( @email.from ).to eq(EXPECTED)
  end

  it "expect `to` to eq #{EXPECTED}" do
    expect( @email.to ).to eq(EXPECTED)
  end

  it "expect `reply_to` to eq #{EXPECTED}" do
    expect( @email.reply_to ).to eq(EXPECTED)
  end
end

Test results all the same

1) MessageMailer expect `reply_to` to eq Aaron Test <[email protected]>

  Failure/Error: expect( @email.reply_to ).to eq(EXPECTED)

    expected: "Aaron Test <[email protected]>"
        got: ["[email protected]"]

   (compared using ==)

Anyone know how to assign [to:, from:, reply_to:] in the email-with-name format?

Am I missing something?

Are there different methods that hold the email headers that I can test against?

Upvotes: 1

Views: 1257

Answers (2)

Aaron Renoir
Aaron Renoir

Reputation: 4391

Ok I got it by testing against the header hash of the email.

This is how to test the values of 'from', 'reply_to' and 'to' in rspec.

describe MessageMailer do
  before do
    @email = MessageMailer.simple
  end

  it "expect `from` to be formatted correctly" do
     expect( @email.header['From'].to_s ).to eq("Aaron Test <[email protected]>")
  end

  it "expect `reply_to` to be formatted correctly" do
     expect( @email.header['Reply-To'].to_s ).to eq("Aaron Test <[email protected]>")
  end

  it "expect `to` to be formatted correctly" do
     expect( @email.header['To'].to_s ).to eq("Aaron Test <[email protected]>")
  end
end

Upvotes: 4

frandroid
frandroid

Reputation: 1412

* Update:

The square brackets you're getting indicate that you're receiving an array. So you need to extract the values out of the array to verify their validity. The reason for this is that you could have multiple addressees, so for example the object could return: ["Aaron Test ", "Renoir "]


As far as I understand, you don't need to use the square brackets, and you don't need to include the quote marks in the string.

These should work:

from: "Aaron Test <[email protected]>",
reply_to: "Aaron Test <[email protected]>"

Upvotes: 0

Related Questions