20

I'm using rspec with the email-spec gem. I'm trying to do:

last_delivery = ActionMailer::Base.deliveries.last
last_delivery.body.should include "This is the text of the email"

But that doesn't work, is there a way to say body, text version? Content-Type: text/text?

Thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

8 Answers8

38

Body is actually a Mail::Body instance. Calling raw_source on it should do the trick:

last_delivery = ActionMailer::Base.deliveries.last
last_delivery.body.raw_source.should include "This is the text of the email"
20

After trying all the above options and failing to get it working (Rails 3.2.13), I found some info in the ruby guide (section 6 is on testing with TestUnit) and got this to work exactly as needed:

last_delivery = ActionMailer::Base.deliveries.last
last_delivery.encoded.should include("This is the text of the email")

Hope that helps!

jeffreymatthias
  • 674
  • 5
  • 8
9

If you have an html template (example.html.erb) you could use:

last_delivery.html_part.body.to_s

Or, if you have a plain-text (example.text.erb) template:

last_delivery.text_part.body.to_s

Source: In Rails why is my mail body empty only in my test?

Giovanni Benussi
  • 3,102
  • 2
  • 28
  • 30
5

you can just call #to_s on it.

last_delivery.to_s.should include "This is the text of the email"

For multipart emails:

last_delivery.first.to_s.should include "This is the text of the email"

Tested & found to be working on Rails 4

CuriousMind
  • 33,537
  • 28
  • 98
  • 137
  • multi-part e-mails, you first need to select the correct part. Updated the answer. if this doesn't work. Let me know – CuriousMind Dec 16 '13 at 14:18
5

Generic way to get body text:

(mail.html_part || mail.text_part || mail).body.decoded

If an email is multipart (mail.multipart?) then its mail.html_part or mail.text_part are defined, otherwise they are nil and mail.body.decoded returns email's content.

You can use also body.to_s instead of body.decoded.

Lev Lukomsky
  • 6,346
  • 4
  • 34
  • 24
0

In Rails 4 the default last_delivery.body.should include "This is the text of the email" works fine for me.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
james
  • 3,989
  • 8
  • 47
  • 102
0

Actually there is no need to send a mail in order to test the content. You could just test:

expect(YourMailer.mail_to_test.body).to include "your string"
Markus Andreas
  • 935
  • 1
  • 13
  • 12
-2
expect(last_delivery).to have_body_text(/This is the text of the email/)

source