Reputation: 110960
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
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
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
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
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
Reputation: 55
expect(last_delivery).to have_body_text(/This is the text of the email/)
Upvotes: -2
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
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
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