sends_notification_emails.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. module SendsNotificationEmailsHelper
  2. # Provides a helper method to check notification email sending for a code block.
  3. #
  4. # @yield [] Description of block
  5. #
  6. # @example
  7. # check_notification do
  8. #
  9. # SomeClass.do_things_and_send_notification
  10. #
  11. # sent(
  12. # template: 'user_device_new',
  13. # user: admin,
  14. # )
  15. # end
  16. #
  17. # @return [nil]
  18. def check_notification
  19. @checking_notification = true
  20. reset_notification_checks
  21. yield
  22. @checking_notification = false
  23. end
  24. # Provides a helper method to check that a notification email wasn't sent.
  25. #
  26. # @param [Hash] args the arguments that get passed to "with hash_including" RSpec matchers
  27. # @see NotificationFactory::Mailer.notification
  28. #
  29. # @example
  30. # not_sent(
  31. # template: 'user_device_new_location',
  32. # user: admin,
  33. # )
  34. #
  35. # @return [nil]
  36. def not_sent(args)
  37. check_in_progress!
  38. expect(NotificationFactory::Mailer).to_not have_received(:notification).with(
  39. hash_including(args)
  40. )
  41. end
  42. # Provides a helper method to check that a notification email was sent.
  43. #
  44. # @param [Hash] args the arguments that get passed to "with hash_including" RSpec matchers
  45. # @see NotificationFactory::Mailer.notification
  46. #
  47. # @example
  48. # sent(
  49. # template: 'user_device_new_location',
  50. # user: admin,
  51. # )
  52. #
  53. # @return [nil]
  54. def sent(args)
  55. check_in_progress!
  56. expect(NotificationFactory::Mailer).to have_received(:notification).with(
  57. hash_including(args)
  58. ).once
  59. end
  60. private
  61. def reset_notification_checks
  62. check_in_progress!
  63. RSpec::Mocks.space.proxy_for(NotificationFactory::Mailer).reset
  64. # to be able to use `have_received` rspec expectations we need
  65. # to stub the class and allow all calls which starts "recording" calls
  66. allow(NotificationFactory::Mailer).to receive(:notification).and_call_original
  67. end
  68. def check_in_progress!
  69. return if @checking_notification
  70. raise "Don't check notification sending without `checking_notification` block around it."
  71. end
  72. end
  73. RSpec.configure do |config|
  74. config.include SendsNotificationEmailsHelper, sends_notification_emails: true
  75. end