sends_notification_emails.rb 2.2 KB

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