rspec-email - 如何获取正文?

AnA*_*ice 15 rspec rspec2 email-spec

我正在使用带有email-spec gem的rspec.我正在尝试:

last_delivery = ActionMailer::Base.deliveries.last
last_delivery.body.should include "This is the text of the email"
Run Code Online (Sandbox Code Playgroud)

但这不起作用,有没有办法说出身体,文字版本?内容类型:文字/文字?

谢谢

小智 32

Body实际上是一个Mail :: Body实例.在其上调用raw_source应该可以解决问题:

last_delivery = ActionMailer::Base.deliveries.last
last_delivery.body.raw_source.should include "This is the text of the email"
Run Code Online (Sandbox Code Playgroud)

  • 只是一个简短的注意事项:如果您使用多部分电子邮件,首先需要选择正确的部分:`last_delivery.parts.first.body.raw_source.should include"这是电子邮件的文本"` (30认同)

jef*_*ias 18

在尝试了上述所有选项并且无法使其正常工作之后(Rails 3.2.13),我在ruby指南中找到了一些信息(第6节是关于使用TestUnit进行测试)并使其完全按照需要工作:

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

希望有所帮助!

  • 当编码的邮件包含由“=”标记的换行符时,这实际上可能会失败,例如“这是电子邮件的=\n文本” (2认同)

Gio*_*ssi 6

如果您有一个 html 模板(example.html.erb),您可以使用:

last_delivery.html_part.body.to_s
Run Code Online (Sandbox Code Playgroud)

或者,如果您有一个纯文本 ( example.text.erb ) 模板:

last_delivery.text_part.body.to_s
Run Code Online (Sandbox Code Playgroud)

来源:在 Rails 中,为什么我的邮件正文仅在我的测试中为空?


Cur*_*ind 5

你可以随便打电话#to_s.

last_delivery.to_s.should include "This is the text of the email"
Run Code Online (Sandbox Code Playgroud)

对于多部分电子邮件:

last_delivery.first.to_s.should include "This is the text of the email"
Run Code Online (Sandbox Code Playgroud)

测试并发现正在开发Rails 4


Lev*_*sky 5

获取正文的通用方法:

(mail.html_part || mail.text_part || mail).body.decoded
Run Code Online (Sandbox Code Playgroud)

如果电子邮件是多部分 ( mail.multipart?) ,则定义其mail.html_part或,否则它们为零并返回电子邮件的内容。mail.text_partmail.body.decoded

您可以使用也body.to_s代替body.decoded