test_helper.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. module ActionMailer
  2. module TestHelper
  3. extend ActiveSupport::Concern
  4. # Asserts that the number of emails sent matches the given number.
  5. #
  6. # def test_emails
  7. # assert_emails 0
  8. # ContactMailer.deliver_contact
  9. # assert_emails 1
  10. # ContactMailer.deliver_contact
  11. # assert_emails 2
  12. # end
  13. #
  14. # If a block is passed, that block should cause the specified number of emails to be sent.
  15. #
  16. # def test_emails_again
  17. # assert_emails 1 do
  18. # ContactMailer.deliver_contact
  19. # end
  20. #
  21. # assert_emails 2 do
  22. # ContactMailer.deliver_contact
  23. # ContactMailer.deliver_contact
  24. # end
  25. # end
  26. def assert_emails(number)
  27. if block_given?
  28. original_count = ActionMailer::Base.deliveries.size
  29. yield
  30. new_count = ActionMailer::Base.deliveries.size
  31. assert_equal original_count + number, new_count, "#{number} emails expected, but #{new_count - original_count} were sent"
  32. else
  33. assert_equal number, ActionMailer::Base.deliveries.size
  34. end
  35. end
  36. # Assert that no emails have been sent.
  37. #
  38. # def test_emails
  39. # assert_no_emails
  40. # ContactMailer.deliver_contact
  41. # assert_emails 1
  42. # end
  43. #
  44. # If a block is passed, that block should not cause any emails to be sent.
  45. #
  46. # def test_emails_again
  47. # assert_no_emails do
  48. # # No emails should be sent from this block
  49. # end
  50. # end
  51. #
  52. # Note: This assertion is simply a shortcut for:
  53. #
  54. # assert_emails 0
  55. def assert_no_emails(&block)
  56. assert_emails 0, &block
  57. end
  58. end
  59. end