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

后端 未结 5 906
灰色年华
灰色年华 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:24

    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
    

提交回复
热议问题