Skip to content

Instantly share code, notes, and snippets.

@danielpuglisi
Forked from abarrak/test_helper.rb
Last active July 29, 2019 09:40
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 danielpuglisi/05364bc1d38a18d747f7d699e16aa1eb to your computer and use it in GitHub Desktop.
Save danielpuglisi/05364bc1d38a18d747f7d699e16aa1eb to your computer and use it in GitHub Desktop.
Perform Enqueued Mail Job in Rails 6 Tests
# Extend in your test_helper.rb or any other `/support` setup you have.
class ActiveSupport::TestCase
# === NOTICE:
# Ensure you have included `ActionMailer::TestHelper` in the test class ..
#
# This method performs any enqueued job during tests manually,
# Helpful when testing the queueing of your jobs and then the result of their execution.
#
# === Author: (abarrak, danielpuglisi)
#
# === 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_emails 1
# assert_enqueued_jobs 1
#
# perform_last_mail_job
#
# assert_emails 1 # make sure to empty ActionMailer::Base.deliveries after each test for correct results
#
# mail = ActionMailer::Base.deliveries.last
# assert_not_nil mail
# assert_equal mail.to, [user.email]
# assert_equal mail.from, ["no-replay@example.com"]
# end
#
# ====
def perform_last_mail_job
# Get last mailer job
last_job = enqueued_jobs.first[:args]
mailer, mail_method, delivery_method = last_job
# Parse job arguments
args = last_job[3]['args']
objects = args.map{|arg| parse_aj_global_id(arg)}
# Perform the last job
perform_enqueued_jobs do
ActionMailer::MailDeliveryJob.perform_now(
mailer,
mail_method,
delivery_method,
args: objects
)
end
end
private
def parse_aj_global_id(arg)
return nil if arg.nil?
gid = arg['_aj_globalid']
GlobalID::Locator.locate(gid)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment