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

问题描述 投票:0回答:1

我有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块起作用。

谢谢

ruby-on-rails rspec rspec-rails
1个回答
0
投票

在第5行,当您期望期望块中出现其他错误时,您正在引发SomeExceptions::InvalidFile异常

raise_error(SomeExceptions::InvalidMailOptions)

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

© www.soinside.com 2019 - 2024. All rights reserved.