Testing return value after raising an exception

14 views
Skip to first unread message

Carlos Rodriguez

unread,
Jun 4, 2018, 8:18:31 PM6/4/18
to rspec
Hello folks, 

I'm trying to test the return value of a method after an exception is called and I'm unsure of how to actually test this. I basically want to throw away the exception to see the return value. See the super contrived example below:

class Foo
  def call
    Bar.new.call
  end
end

class Bar
  def call
    Meep.new.call
  end
end

class Meep
  def call
    "no error"
  rescue ArgumentError
    "error"
  end
end

allow_any_instance_of(Meep).to receive(:call).and_raise(ArgumentError)
expect(Foo.new.call).to eq "error"




Myron Marston

unread,
Jun 10, 2018, 1:42:44 AM6/10/18
to rs...@googlegroups.com

Hi Carlos,

It’s not clear to me what you’re trying to accomplish with that example. Meep#call has a rescue clause but the code being rescued involves no method calls ("no error" is not a method call) and, barring something truly bizarre like a busted ruby installation, cannot raise any sort of exception. As there’s no possibility of an ArgumentError being raised, there’s no point in rescuing it (or in trying to write a test to cover the possibility of an exception being raised).

In addition, allow_any_instance_of(Meep).to receive(:call).and_raise(ArgumentError) completely replaces your existing implementation of Meep#call including the rescue ArgumentError.

I’m not sure what to suggest since your example doesn’t make sense to me.

Myron


--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+unsubscribe@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/9a05e52f-21c5-49bf-808b-e826261f9936%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jon Rowe

unread,
Jun 10, 2018, 5:44:56 PM6/10/18
to rs...@googlegroups.com
Hi Carlos

You need to stub a method within your definition of call that will raise an error, like Myron points out currently you are overwriting your definition and so the rescue has no effect.

Cheers
Jon

To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.

To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/9a05e52f-21c5-49bf-808b-e826261f9936%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.

To post to this group, send email to rs...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages