在Rails中,为什么我的邮件主体只在我的测试中空了?

我有一个actionmailer类和相关的开销,它完美地工作。 但是,在我的unit testing(rails default minitest)中,电子邮件正文是空的。 这是为什么?

我的邮件课:

class TermsMailer < ApplicationMailer default from: "info@domain.com" def notice_email(user,filename) @user = user @file = filename mail(to: "info@domain.com", subject: 'Data downloaded') end end 

我的测试:

 require 'test_helper' class TermsMailerTest < ActionMailer::TestCase test "notice" do email = TermsMailer.notice_email(users(:me),'file.ext').deliver_now assert_not ActionMailer::Base.deliveries.empty? assert_equal ['info@domain.com'], email.from assert_equal ['info@domain.com'], email.to assert_equal 'Data downloaded', email.subject assert_equal 'arbitrary garbage for comparison', email.body.to_s end end 

此邮件的视图不是空白,并且实际上在电子邮件中发送了正确的内容。 那么为什么我的测试中的电子邮件正文空白?

您可能有两个版本的电子邮件模板( text.erbhtml.erb )。

如果是这样,您可以将email.text_part.body.to_s用于纯文本电子邮件,将email.html_part.body.to_s用于HTML版本。