46
loading...
This website collects cookies to deliver better user experience
queue_adapter
set to :inline
, then a deliver_later
will happen synchronously. So, the email will immediately end up in the deliveries
box.describe '#welcome' do
it 'sends the welcome email to the user' do
valid_params = { user_id: user.id }
expect {
post :invite, params: valid_params
}.to change { ActionMailer::Base.deliveries.count }.by(1)
end
end
queue_adapter
is set to something like :test
or async
. In this case, the email is going to be queued in the app's job queue. Since it is not immediately being sent, the expectation will have to be about the job queue instead.describe '#welcome' do
it 'sends the welcome email to the user' do
valid_params = { user_id: user.id }
expect {
post :invite, params: valid_params
}.to have_enqueued_job(ActionMailer::DeliveryJob)
end
end
describe '#welcome' do
it 'sends the welcome email to the user' do
valid_params = { user_id: user.id }
expect {
post :invite, params: valid_params
}.to have_enqueued_job(ActionMailer::DeliveryJob)
.with('UserMailer', 'welcome', 'deliver_now', Integer)
end
end
deliver_later
gets called. We take things a step further with the receive
method by using its &block
argument to make assertions about the values passed to the mailer method.describe '#welcome' do
it 'sends the welcome email to the user' do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(UserMailer).to receive(:welcome) do |user_id|
expect(user_id).to match(user.id)
end.and_return(mail_double)
valid_params = { user_id: user.id }
post :invite, params: valid_params
end
end
# spec/support/mailer_matcher.rb
require "rspec/expectations"
RSpec::Matchers.define :send_email do |mailer_action|
match do |mailer_class|
message_delivery = instance_double(ActionMailer::MessageDelivery)
expect(mailer_class).to receive(mailer_action).and_return(message_delivery)
allow(message_delivery).to receive(:deliver_later)
end
end
describe '#welcome' do
it 'sends the welcome email to the user' do
expect(UserMailer).to send_email(:welcome)
valid_params = { user_id: user.id }
post :invite, params: valid_params
end
end