Rails - 如何测试ActionMailer发送的特定附件?

时间:2013-01-11 20:32:08

标签: ruby-on-rails-3 unit-testing ruby-on-rails-3.2 actionmailer

在我的ActionMailer :: TestCase测试中,我期待:

@expected.to      = BuyadsproMailer.group_to(campaign.agency.users)
@expected.subject = "You submitted #{offer_log.total} worth of offers for #{offer_log.campaign.name} "
@expected.from    = "BuyAds Pro <feedback@buyads.com>"
@expected.body    = read_fixture('deliver_to_agency')

@expected.content_type = "multipart/mixed;\r\n boundary=\"something\""
@expected.attachments["#{offer_log.aws_key}.pdf"] = {
  :mime_type => 'application/pdf',
  :content => fake_pdf.body
}

并将我的邮件存根以获取fake_pdf而不是通常从S3获取的真实PDF,以便我确定PDF的正文匹配。

但是,我收到这个很长的错误,告诉我一封电子邮件是预期的,但电子邮件略有不同:

<...Mime-Version: 1.0\r\nContent-Type: multipart/mixed\r\nContent-Transfer-Encoding: 7bit...> expected but was
<...Mime-Version: 1.0\r\nContent-Type: multipart/mixed;\r\n boundary=\"--==_mimepart_50f06fa9c06e1_118dd3fd552035ae03352b\";\r\n charset=UTF-8\r\nContent-Transfer-Encoding: 7bit...>

我不匹配生成的电子邮件的字符集或部分边界。

如何定义或存储我预期的电子邮件的这一方面?

2 个答案:

答案 0 :(得分:42)

以下是我从特定附件的rspec测试中复制的示例,希望它有所帮助(可以通过调用邮件程序方法创建邮件或在调用.deliver后查看交付数组):

  mail.attachments.should have(1).attachment
  attachment = mail.attachments[0]
  attachment.should be_a_kind_of(Mail::Part)
  attachment.content_type.should be_start_with('application/ics;')
  attachment.filename.should == 'event.ics'

答案 1 :(得分:2)

我有类似的地方想要检查附件中csv的内容。我需要这样的内容,因为看起来\r已插入换行符:

expect(mail.attachments.first.body.encoded.gsub(/\r/, '')).to(
  eq(
    <<~CSV
      "Foo","Bar"
      "1","2"
    CSV
  )
)