预期的异常,但未引发任何异常Rails Mailer(似乎未调用raising-exception方法)

时间:2020-04-22 01:37:08

标签: ruby-on-rails rspec rspec-rails

我正在使用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显示我之前期望的失败/错误:

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放入notify方法中,发现: 如果我们使用expect块,即expect.{...}.to,则不会执行notify方法。 但是,如果我们使用普通的expect,即expect(...).to,则执行notify方法。

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

谢谢

2 个答案:

答案 0 :(得分:1)

在第5行,当您期望期望块中出现不同的错误时,您将引发SomeExceptions::InvalidFile异常

raise_error(SomeExceptions::InvalidMailOptions)

要么替换期望的异常,要么仅使用raise_error捕获所有异常,而不传递任何错误类(不推荐,但出于测试目的)。

答案 1 :(得分:0)

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

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