Como testar ActionMailer + ActiveJob com Rspec

Suponha que temos esse e-mail:

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

Que é entregue usando padrão ActiveJob & método de ActionMailer:
UserMailer.welcome_email(user).deliver_later.

(você também precisa definir config.active_job.queue_adapter = :sidekiq[ou algum outro adaptador] em seu método de application.rbuso deliver_later).

E quero testá-lo com 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