xqcq7q
Last Updated: February 25, 2016
·
4.103K
· lakesare
None

How to test ActionMailer + ActiveJob with Rspec

Suppose we have such email:

class UserMailer < ApplicationMailer
    def welcome_email(user)
        @user = user
        mail(to: @user.email, subject: 'Welcome')
    end
end

That is delivered using default ActiveJob & ActionMailer's method:
UserMailer.welcome_email(user).deliver_later.

(you also need to set config.active_job.queue_adapter = :sidekiq [or some other adapter] in your application.rb to use deliver_later method).

And want to test it with Rspec.

require 'rails_helper'
include ActiveJob::TestHelper
let(:user){ User.create(email: 'hi@hi.com') }

#test that job is enqueued
it 'job is created' do
    ActiveJob::Base.queue_adapter = :test
    expect {
        UserMailer.welcome_email(self).deliver_later
    }.to have_enqueued_job.on_queue('mailers')
end

# since we have config.action_mailer.delivery_method  set to :test in our :test.rb, all 'sent' emails are gathered into the ActionMailer::Base.deliveries array.
it 'welcome_email is sent' do
    expect {
        perform_enqueued_jobs do
            UserMailer.welcome_email(user).deliver_later
        end
    }.to change { ActionMailer::Base.deliveries.size }.by(1)
end

it 'welcome_email is sent to the right user' do
    perform_enqueued_jobs do
        UserMailer.welcome_email(user).deliver_later
    end

    mail = ActionMailer::Base.deliveries.last
    expect(mail.to[0]).to eq user.email
end
Say Thanks
Respond

1 Response
Add your response

26850
Fisheye

Helpful reference

over 1 year ago ·