AnApprentice
AnApprentice

Reputation: 110960

rspec-email - How to get the body text?

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

Upvotes: 20

Views: 13932

Answers (8)

Markus Andreas
Markus Andreas

Reputation: 993

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"

Upvotes: 0

Lev Lukomskyi
Lev Lukomskyi

Reputation: 6667

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.

Upvotes: 5

Giovanni Benussi
Giovanni Benussi

Reputation: 3500

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?

Upvotes: 11

james
james

Reputation: 4049

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

Upvotes: 0

Hugo Stieglitz
Hugo Stieglitz

Reputation: 55

expect(last_delivery).to have_body_text(/This is the text of the email/)

source

Upvotes: -2

CuriousMind
CuriousMind

Reputation: 34135

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

Upvotes: 5

jeffreymatthias
jeffreymatthias

Reputation: 674

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!

Upvotes: 20

Alberto F. Capel
Alberto F. Capel

Reputation: 721

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"

Upvotes: 40

Related Questions