Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_basics.html#sending-multipart-emails

I have both mailer templates in text and html formats, but it looks like my tests are only checking the HTML portion. Is there a way to check the text template separately?

Is it only checking the HTML view because it's first in the default order?

like image 299
cmhobbs Avatar asked Jun 27 '11 00:06

cmhobbs


1 Answers

To supplement, nilmethod's excellent answer, you can clean up your specs by testing both text and html versions using a shared example group:

spec_helper.rb

def get_message_part (mail, content_type)   mail.body.parts.find { |p| p.content_type.match content_type }.body.raw_source end  shared_examples_for "multipart email" do   it "generates a multipart message (plain text and html)" do     mail.body.parts.length.should eq(2)     mail.body.parts.collect(&:content_type).should == ["text/plain; charset=UTF-8", "text/html; charset=UTF-8"]   end end 

your_email_spec.rb

let(:mail) { YourMailer.action }  shared_examples_for "your email content" do   it "has some content" do     part.should include("the content")   end end  it_behaves_like "multipart email"  describe "text version" do   it_behaves_like "your email content" do     let(:part) { get_message_part(mail, /plain/) }   end end  describe "html version" do   it_behaves_like "your email content" do     let(:part) { get_message_part(mail, /html/) }   end end 
like image 166
Lachlan Cotter Avatar answered Sep 28 '22 02:09

Lachlan Cotter