Rails – How to test that ActionMailer sent a specific attachment

actionmailerruby-on-rails-3ruby-on-rails-3.2unit testing

In my ActionMailer::TestCase test, I'm expecting:

@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
}

and stub my mailer to get fake_pdf instead of a real PDF normally fetched from S3 so that I'm sure the bodies of the PDFs match.

However, I get this long error telling me that one email was expected but got a slightly different email:

<...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...>

I'm not matching the charset or part-boundary of the generated email.

How do I define or stub this aspect of my expected emails?

Best Answer

Here's an example that I copied from my rspec test of a specific attachment, hope that it helps (mail can be creating by calling your mailer method or peeking at the deliveries array after calling .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'