Testing ActionMailer multipart emails(text and html version) with RSpec

后端 未结 5 992
灰色年华
灰色年华 2021-01-30 22:06

I\'m currently testing my mailers with RSpec, but I\'ve started setting up multipart emails as described in the Rails Guides here: http://guides.rubyonrails.org/action_mailer_b

5条回答
  •  你的背包
    2021-01-30 22:18

    To make things even simpler, you can use

    message.text_part    and
    message.html_part
    

    to find the respective parts. This works even for structured multipart/alternative messages with attachments. (Tested on Ruby 1.9.3 with Rails 3.0.14.)

    These methods employ some kind of heuristic to find the respective message parts, so if your message has multiple text parts (e.g. as Apple Mail creates them) it might fail to do the "right thing".

    This would change the above method to

    def body_should_match_regex(mail, regex)
     if mail.multipart?
      ["text", "html"].each do |part|
       mail.send("#{part}_part").body.raw_source.should match(regex)
      end
     else
      mail.body.raw_source.should match(regex)
     end
    end
    

    which works for both plaintext (non-multipart) messages and multipart messages and tests all message bodies against a specific regular expression.

    Now, any volunteers to make a "real" RSpec matcher out of this? :) Something like

    @mail.bodies_should_match /foobar/
    

    would be a lot nicer ...

提交回复
热议问题