mardi 23 mars 2021

Ruby: rspec not catching exceptions?

I'm having trouble grasping how rspec handles exceptions. In this case, I'd like to ensure the exception is properly caught and returned in a formatted message.

Consider the following:

class Sample

  def calculate(x, y)
    begin
      add(x,y)
    rescue Exception => e
      return "Exception occured: #{e}"
    end
  end
  
  def add(x, y)
    x + y
  end
end

With a spec like so:

describe "sample" do
  it "adds numbers" do
    test = Sample.new

    allow(test)
      .to receive(:calculate)
      .with(1, 2) { Exception.new('foo') }

    expect(test.calculate(1,2)). to eq 'Exception occurred: foo'
  end
end

I would expect the exception to be properly caught by rspec as it is by the method calculate itself, however, I receive the following when executing the spec:

Failures:

  1) sample adds numbers
     Failure/Error: expect(test.calculate(1,2)). to eq 'Exception occurred: foo'
     
       expected: "Exception occurred: foo"
            got: #<Exception: foo>
     
       (compared using ==)
     
       Diff:
       @@ -1,2 +1,2 @@
       -"Exception occurred: foo"
       +#<Exception: foo>

But when testing the rescue via irb, it's properly handled:

irb(main):001:0> test = Sample.new()
=> #<Sample:0x000055d0f864db50>
irb(main):002:0> test.calculate("i", 2)
=> "Exception occured: no implicit conversion of Integer into String"
irb(main):003:0> 

I'm very new to rspec so any feedback is welcome :D

Aucun commentaire:

Enregistrer un commentaire