Messageが作られるとAdminにmailが飛ぶ。Messageにemail addressが有ったら更に警告メールが飛ぶ、というシステムがあります。after_commitで行っていたため、そのメールを削除しても警告メールが飛んでしまう! ということがあり修正を行うにあたって rspecを書こうとして困っています。
class Message < ApplicationRecord after_commit :send_message_notification, on: :create after_commit :send_content_violation_notice_mail_to_admin, if: :message_violation? def send_message_notification AdminMailer.with(message_id: id, title: title).approval_request.deliver end def send_content_violation_notice_mail_to_admin return if (violations = message_contains?).blank? AdminMailer.with(message: self, violation: violations.join(' および ')) .content_violation.deliver end end class AdminMailer < ApplicationMailer def approval_request # 省略 mail(subject: t('mailer.admin.approval_request.subject')) end def content_violation # 省略 mail(subject: 'メールアドレスのあるメッセージのお知らせ') end end
「メソッドが呼ばれる」のテストですとよく使うのは
it 'メソッドが呼ばれる' do allow(admin_mailer).to receive(:content_violation) subject # で MessageをPost expect(admin_mailer).to_not have_received(:content_violation) end
かと思いますが、今回 AdminMailerのinstanceを明示的に作っているわけではないので、allow_any_inctance_of(AdminMailer).to receive(:content_violation)
とせざるを得ない? ので have_received が使えない?
やむを得ず
it 'メールが2通出る' do subject # で MessageをPost expect { subject }.to change(ActionMailer::Base.deliveries, :size).by 2
とかしてますが、これだと Mailerのテストも被ってしまってるのが気持ちが悪く、
かつ「呼ばれているのが content_violation と approval_request なのか?」 も確認できず。
「このMailerのこのmethodが確かに呼ばれている」というのを確かめる良い方法は無いでしょうか。
Rails 6
ruby 2.6.5
Linux
0 コメント