如何强制 ActionMailer 错误进行测试?

How can I force an ActionMailer error for testing?

我有这个代码可以根据条件发送电子邮件。如果出现错误,它应该捕获无法像这样在数组中发送的帐户:

def process_email(delivery_method_name)
  begin
    Account::Access.new(account).spam! if delivery_method_name == 'mark_as_spam'
    AccountMailer.send("#{delivery_method_name}", account).deliver_now
  rescue
    @first_notification_error << account.id
    @second_notification_failure << account.id
    @third_notification_failure << account.id
    @fourth_notification_error << account.id
    @fourth_notification_failure << account.id
    return
  end
  update_reverification_fields
end

所以在我的 test.rb 文件中,我希望能够测试 account.id 是否在 @first_notification_error 和其他容器中。虽然我不太清楚如何做到这一点。我在另一个 post 中读到将这段代码放在 development.rb and/or test.rb config.action_mailer.raise_delivery_errors = true 中,但我认为这不是我要找的。有没有一种方法可以在我的测试中引发错误,也许是用存根或类似的东西?

你需要模拟 AccountMailer。在调用您正在测试的代码之前放置此行:

delivery_method = 'some method on mailer that you want to mock'
allow(AccountMailer).to receive(delivery_method).and_raise("boom")