Perform email jobs in #assert_emails

Perform enqueued delivery jobs in #assert_emails and #assert_no_emails.
This commit is contained in:
Gannon McGibbon 2018-03-12 14:30:25 -04:00 committed by Gannon McGibbon
parent 309bb6c4d0
commit 96218b4568
2 changed files with 29 additions and 5 deletions

View File

@ -14,7 +14,7 @@ module ActionMailer
# assert_emails 0
# ContactMailer.welcome.deliver_now
# assert_emails 1
# ContactMailer.welcome.deliver_now
# ContactMailer.welcome.deliver_later
# assert_emails 2
# end
#
@ -28,17 +28,19 @@ module ActionMailer
#
# assert_emails 2 do
# ContactMailer.welcome.deliver_now
# ContactMailer.welcome.deliver_now
# ContactMailer.welcome.deliver_later
# end
# end
def assert_emails(number)
def assert_emails(number, &block)
if block_given?
original_count = ActionMailer::Base.deliveries.size
yield
perform_enqueued_jobs(only: [ActionMailer::DeliveryJob, ActionMailer::Parameterized::DeliveryJob], &block)
new_count = ActionMailer::Base.deliveries.size
assert_equal number, new_count - original_count, "#{number} emails expected, but #{new_count - original_count} were sent"
else
assert_equal number, ActionMailer::Base.deliveries.size
perform_enqueued_jobs(only: [ActionMailer::DeliveryJob, ActionMailer::Parameterized::DeliveryJob]) do
assert_equal number, ActionMailer::Base.deliveries.size
end
end
end

View File

@ -69,6 +69,16 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
end
def test_assert_emails_with_enqueued_emails
assert_nothing_raised do
assert_emails 1 do
silence_stream($stdout) do
TestHelperMailer.test.deliver_later
end
end
end
end
def test_repeated_assert_emails_calls
assert_nothing_raised do
assert_emails 1 do
@ -105,6 +115,18 @@ class TestHelperMailerTest < ActionMailer::TestCase
end
end
def test_assert_no_emails_with_enqueued_emails
error = assert_raise ActiveSupport::TestCase::Assertion do
assert_no_emails do
silence_stream($stdout) do
TestHelperMailer.test.deliver_later
end
end
end
assert_match(/0 .* but 1/, error.message)
end
def test_assert_emails_too_few_sent
error = assert_raise ActiveSupport::TestCase::Assertion do
assert_emails 2 do