【问题标题】:RSpec test Rollbar called in method where error is raised在引发错误的方法中调用 RSpec 测试 Rollbar
【发布时间】:2020-02-26 06:47:34
【问题描述】:

我能够测试 Rollbar.warning 是否已被调用,但是当它在同样引发错误的方法中被调用时,它会因为引发错误而失败,并且它会跳过 Rollbar.warning

  context 'unauthorized' do
    before do
      allow(Rollbar).to receive(:warning)
    end

    it 'sends a warning to rollbar' do
      subject.send(:log_and_raise_error)

      expect(Rollbar).to have_received(:warning)
    end
  end

这是我正在测试的方法:

  def log_and_raise_error
    Rollbar.warning(
      "Not authorized error accessing resource #{ResourceID}"
    )

    raise NotAuthorized
  end

但是当我运行规范时,它失败了:

 1) Authorization unauthorized sends a warning to rollbar
     Failure/Error: subject.send(:log_and_raise_error)

     NotAuthorized

有什么想法可以解决这个错误并仍然测试 Rollbar?

【问题讨论】:

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


    【解决方案1】:

    您可以预料到错误或挽救它:

    预计错误:

        it 'sends a warning to rollbar' do
          expect { subject.send(:log_and_raise_error) }.to raise_error NotAuthorized
    
          expect(Rollbar).to have_received(:warning)
        end
    

    救援错误:

        it 'sends a warning to rollbar' do
          subject.send(:log_and_raise_error) rescue NotAuthorized
    
          expect(Rollbar).to have_received(:warning)
        end
    

        it 'sends a warning to rollbar' do
          begin
            subject.send(:log_and_raise_error)
          rescue NotAuthorized
          # noop
          end
          expect(Rollbar).to have_received(:warning)
        end
    

    【讨论】:

    • 关键只是增加了引发错误的预期
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多