2

我能够测试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?

4

1 回答 1

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
于 2019-10-30T22:23:50.923 回答