Expected Exception but nothing was raised Rails Mailer(引发异常的方法似乎没有被调用)

Expected Exception but nothing was raised Rails Mailer (the raising-exception method seems not to be called)

我有 RSpec 预计会引发一些异常。但是,在调用该方法时,出现错误:expected Exception but nothing was raised

我的代码:

require 'rails_helper'

RSpec.describe ReportMailer, type: :mailer do
  let(:csv_file) { "data\n1\n2" }
  let(:filename) { 'dummy.csv' }
  let(:options) do
    {
      filename: filename,
      to: user.email,
      subject: "Transaction Report - #{filename}"
    }
  end

   it 'raise error' do
     expect do
       ReportMailer.notify(options, nil)
     end.to raise_error(SomeExceptions::InvalidFile)
   end

end

问题是,如果我只使用普通的 expect 调用,假设

expect(described_class.notify(dummy_options, nil)).to eq 1

RSpec 显示我之前期望的 failure/error:

Failures:

  1) ReportMailer raise error
     Failure/Error: raise SomeExceptions::InvalidFile

     SomeExceptions::InvalidFile:
       The file is invalid
     # ./app/mailers/report_mailer.rb:5:in `notify'
     # ./spec/mailers/report_mailer_spec.rb:37:in `block (2 levels) in <top (required)>'

我的通知方法如下:

require 'some_cms_exceptions'

class ReportMailer < ApplicationMailer
  def notify(options, csv)
    binding.pry
    raise SomeExceptions::InvalidFile

    validate(options)

    attachments[options[:filename]] = { mime_type: 'text/csv', content: csv }
    mail(to: options[:to], subject: options[:subject])
  end

  private

  def validate(options)
    raise SomeExceptions::InvalidMailOptions unless !options[:to].blank? && !options[:filename].blank?
  end
end

然后我将 binding.pry 放在通知方法中,发现: 如果我们使用 expect 块,即 expect.{...}.to,则不会执行通知方法。 但是如果我们使用正常的expect,即expect(...).to,通知方法被执行。

我可以知道它为什么会这样吗?因为其他 SO 问题表明它可以通过使用 expect 块来工作。

谢谢

在第 5 行你引发了 SomeExceptions::InvalidFile 异常,而你期望在期望块中出现不同的错误

raise_error(SomeExceptions::InvalidMailOptions)

要么替换预期的异常,要么只使用 raise_error 捕获所有异常而不传递任何错误 class(不推荐,但为了测试)。

答案如@amit-patel 所评论,我们需要添加deliver_now 才能真正执行mailer RSpec 测试用例。

it 'should send email ' do
 expect { ReportMailer.notify(options, nil).deliver_now }.to raise_error(SomeExceptions::InvalidMailOptions)
end