nothing-special-here
nothing-special-here

Reputation: 12568

Rspec - How to test if mailer is using proper template

There is a lot info about how to test mailers.

But I haven't found any resources how to test mailer to check if they REALLY use correct template.

example:

class NewsletterMailer < ActionMailer::Base
  include SendGrid
  default from: -> { SystemConfiguration.newsletter_from_email }

  def send_newsletter_to_groups(newsletter_campaign_id, group_ids)
    newsletter_campaign = NewsletterCampaign.find newsletter_campaign_id
    emails = Group.where(:id => group_ids).map(&:emails).flatten
    build_and_send_email(newsletter_campaign, emails)
  end
end

on app/views/newsletter_mailer/send_newsletter_to_group.html.erb I have typo.

I wrote send_newsletter_to_group.html.erb instead of send_newsletter_to_groups.html.erb

My spec still pass:

require "spec_helper"

describe NewsletterMailer do

  before { create(:system_configuration) }
  let(:newsletter) { create(:newsletter_campaign) }

  describe '.send_newsletter_to_groups' do
    before do
      create(:system_configuration)
      create_list(:group, 3)
      create_list(:user, 2, groups: [Group.first], newsletter_subscription: true)
      create_list(:user, 2, groups: [Group.last], newsletter_subscription: true)
      create_list(:user, 2, name: "pippo")
    end
    let(:group_ids) { Group.pluck(:id) }
    subject { NewsletterMailer.send_newsletter_to_groups(newsletter.id, group_ids) }

    its(:to) { should == User.where("name != 'pippo'").map(&:email) }
    its(:from) { should be_present }
    its(:subject) { should be_present }
  end

end

But email doesn't contain body.

It just send blank email, cuz at the name of the partial (send_newsletter_to_group.html.erb) I got typo.

How to test this? In Mailer.

Upvotes: 5

Views: 1513

Answers (1)

Matt Gibson
Matt Gibson

Reputation: 14949

I use email spec for this.

it "should contain the user's message in the mail body" do
  @email.should have_body_text(/Jojo Binks/)
end

Just look for some text that you know is part of the template.

Upvotes: 0

Related Questions