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