【问题标题】:Rails 4, RSpec 3.2 - how to mockup ActionMailer's deliver_now method to raise exceptionsRails 4, RSpec 3.2 - 如何模拟 ActionMailer 的 Deliver_now 方法来引发异常
【发布时间】:2015-07-11 05:56:16
【问题描述】:

环境

Ruby 2.2.1、Rails 4.2.0、rspec-core 3.2.2、rspec-expectations 3.2.0、rspec-mocks 3.2.1、rspec-rails 3.2.1、rspec-support 3.2.2

我有以下方法

def send_event_alert_email(event_id)
  event = Event.find_by(id: event_id)
  ...
  ...     
  ...
  EventAlertMailer.event_alert(event_id).deliver_now

  create_alert(event)
end

我需要编写规范以确保create_alert(event)EventAlertMailer.event_alert(event_id).deliver_now 引发任何异常时不会被调用。所以基本问题是我如何模拟deliver_now 来引发它可能实际抛出的异常。

【问题讨论】:

    标签: actionmailer ruby-on-rails-4.2 rspec3 ruby-2.2


    【解决方案1】:

    这里是如何测试 deliver_now 方法:

    describe EventAlertMailer do
      it 'sends email' do
        delivery = double
        expect(delivery).to receive(:deliver_now).with(no_args)
    
        expect(EventAlertMailer).to receive(:event_alert)
          .with(event_id)
          .and_return(delivery)
    
        MyClass.send_event_alert_email
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 2021-04-12
      • 2014-04-04
      • 2013-03-09
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多