Skip to content

Instantly share code, notes, and snippets.

@tomohiro
Last active December 4, 2020 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomohiro/dfa7362cd066dd87f25f40bdd6856513 to your computer and use it in GitHub Desktop.
Save tomohiro/dfa7362cd066dd87f25f40bdd6856513 to your computer and use it in GitHub Desktop.
Mail::Matchers example
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'actionmailer', '6.0.3.4'
gem 'rspec', '3.10.0'
end
require 'action_mailer'
ActionMailer::Base.delivery_method = :test
class NotificationsMailer < ActionMailer::Base
default from: 'from@example.com'
def signup
mail(to: 'to@example.org', subject: 'Signup') do |format|
format.text { render plain: 'Hi' }
end
end
end
require 'rspec/autorun'
RSpec.configure do |config|
config.include Mail::Matchers, type: :mailer
end
RSpec.describe NotificationsMailer, type: :mailer do
before do
ActionMailer::Base.deliveries.clear
end
describe '#signup' do
# @see: https://relishapp.com/rspec/rspec-rails/v/3-9/docs/mailer-specs/mailer-spec
context 'when using RSpec mailer examples' do
subject(:mail) { described_class.signup }
it 'renders the headers' do
expect(mail.subject).to eq('Signup')
expect(mail.to).to eq(['to@example.org'])
expect(mail.from).to eq(['from@example.com'])
end
it 'renders the body' do
expect(mail.body.encoded).to match('Hi')
end
it 'sends the mail' do
expect { mail.deliver_now }.to change { ActionMailer::Base.deliveries.count }
end
end
# @see: https://github.com/mikel/mail#using-mail-with-testing-or-specing-libraries
context 'when using Mail::Matchers' do
subject(:mail) { described_class.signup.deliver_now }
it { is_expected.to have_sent_email }
it { is_expected.to have_sent_email.from('from@example.com') }
it { is_expected.to have_sent_email.to('to@example.org') }
it { is_expected.to have_sent_email.with_subject('Signup') }
it { is_expected.to have_sent_email.with_body('Hi') }
end
end
end
@tomohiro
Copy link
Author

tomohiro commented Dec 4, 2020

$ ruby ./use_mail_matchers_when_test_action_mailer.rb -fd

NotificationsMailer
  #signup
    when using RSpec mailer examples
      renders the headers
      renders the body
      sents the mail
    when using Mail::Matchers
      is expected to send a matching email
      is expected to send a matching email
      is expected to send a matching email
      is expected to send a matching email
      is expected to send a matching email

Finished in 0.27858 seconds (files took 0.61162 seconds to load)
8 examples, 0 failures

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment