Test rails mailer with RSpec

(1) Consider you have a notification mailer to send an email when some events happen. E.g.

class NotificationMailer < ApplicationMailer

  def report_event(events, email)

    return if events.nil? || events.size == 0
    return if email.blank?

    @events = events
    mail(to: email, subject: 'Events Notification')
  end

end

(2) Now this mailer method supposes to:

  • Send an email according to the supplied email address.
  • Send an email if at least 1 event happens.
  • Send an email with title "Events Notification".

(3) To test above specification with RSpec. First, we need to setup a test environment, so the test will not actually send an email during the testing.

before(:each) do
  ActionMailer::Base.delivery_method = :test
  ActionMailer::Base.perform_deliveries = true
  ActionMailer::Base.deliveries = []
end

after(:each) do
  ActionMailer::Base.deliveries.clear
end

(4) Then, you can add your test spec.

it 'should not proceed if email is empty' do
  NotificationMailer.report_event(%w(1 2 3 4 5), '').deliver_now
  expect(ActionMailer::Base.deliveries.count).to eq(0)
end

it 'should not proceed if there is no event' do
  NotificationMailer.report_event([], 'calvin@atomnode.com').deliver_now
  expect(ActionMailer::Base.deliveries.count).to eq(0)
end

it 'should send an email' do
  NotificationMailer.report_event(%w(1 2 3 4 5), 'email@destination.com').deliver_now
  expect(ActionMailer::Base.deliveries.count).to eq(1)
end

it 'sends to the correct receiver' do
  NotificationMailer.report_event(%w(1 2 3 4 5), 'email@destination.com').deliver_now
  expect(ActionMailer::Base.deliveries.first.to.first).to eq('email@destination.com')
end

it 'should set the subject correctly' do
  NotificationMailer.report_event(%w(1 2 3 4 5), 'email@destination.com').deliver_now
  expect(ActionMailer::Base.deliveries.first.subject).to eq('Events Notification')
end

AI Summary
Chrome On-device AI 2024-12-06 17:56:39

Share Article