简体   繁体   中英

Rspec testing raising and rescue of method

Is there a way to rspec test if an error was raised and rescued? If I have a rescue, my rspec test does not see the raised error, only results in the rescue?

module MyApp
  def some_method(msg)
     raise StandardError.new(msg)
  end

  def second_method(msg)
    begin
      count = 0
      some_method(msg)
    rescue StandardError=> e
      puts e
      count = 1
    end
  end
end

RSpec.describe Myapp do
  describe "#some_method" do
    it "should raise error" do
       expect {
        some_method("this is an error")
      }.to raise_error(StandardError) {|e|
        expect(e.message).to eql "this is an error"
      }
    end
  end

  # this fails, as the error is not raised
  describe "#second_method" do
    it should raise error and rescue do
      expect {
        a = second_method("this is an error and rescue")
      }.to raise_error(StandardError) {|e|
        expect(e.message).to eql "this is an error and rescue"
        expect(a) = 1
      }
    end
  end
end

You generally don't want to raise or rescue StandardError directly because it's pretty uninformative, and won't catch errors outside of the StandardError hierarchy . Instead, you generally want to test that a specific exception was raised, or that a specific error class or error message was raised.

If you know the custom or built-in exception class that you want, or the specific error message, then test for that explicitly. For example:

it 'should raise an ArgumentError exception' do
  expect { MyApp.new.foo }.to raise_error(ArgumentError)
end

it 'should raise MyCustomError' do
  expect { MyApp.new.foo }.to raise_error(MyCustomError)
end

it 'should raise StandardError with a custom message' do
  msg = 'this is a custom error and rescue'
  expect { MyApp.new.foo }.to raise_error(msg)
end

If you don't know (or care about) the specific exception or message that should be raised, but you expect some exception to interrupt the execution flow, then you should use a bare raise_error matcher. For example:

it "should raise an exception" do
  expect { MyApp.new.foo }.to raise_error
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM