Skip to content

Instantly share code, notes, and snippets.

@abarrak
Last active June 24, 2022 11:58
Show Gist options
  • Save abarrak/99773e1bf295f927a52f5493c7742854 to your computer and use it in GitHub Desktop.
Save abarrak/99773e1bf295f927a52f5493c7742854 to your computer and use it in GitHub Desktop.
Perform Enqueued Mail Job in Rails Tests
# Extend in your test_helper.rb or any other `/supprot` setup you have.
class ActiveSupport::TestCase
##
# === NOTICE:
# Ensure you have `ActionMailer::TestHelper` in the test class ..
#
# This method performs any enqueued job during tests manually,
# Helpful when testing the queueing of your jobs then the result of their execution.
#
# === Author: (abarrak)
#
# === returns: the result of the job execution.
#
# === example: (integration test for ActiveJob/ActionMailer)
#
# test "my action mailer" do
# post signup_url, params: @valid_params
#
# # .. other assertions ..
#
# assert_enqueued_jobs 1
# assert_enqueued_emails 1
# assert_no_emails
# assert_empty ActionMailer::Base.deliveries
#
# perform_lastest_mail_job
#
# assert_emails 1
# assert_not_empty ActionMailer::Base.deliveries
# mail = ActionMailer::Base.deliveries.last
# assert_not_nil mail
# assert_equal mail.to, [user.email]
# assert_equal mail.from, ["[email protected]"]
# # ....
# end
#
# ====
def perform_lastest_mail_job
last_job = enqueued_jobs.first[:args]
gid = last_job.pop['_aj_globalid']
last_job << GlobalID::Locator.locate(gid)
perform_enqueued_jobs { ActionMailer::DeliveryJob.perform_now(*last_job) }
end
end