Raising a mocked exception

17 views
Skip to first unread message

Asher Shockley

unread,
Apr 11, 2018, 3:59:16 PM4/11/18
to rspec
Is it possible to have a mocked method raise a mocked object instead of a real instance of Exception?

https://gist.github.com/david-shockley-beeline/008ea9122e62b051b3614d07a36fae23

Thanks

Myron Marston

unread,
Apr 11, 2018, 4:01:31 PM4/11/18
to rs...@googlegroups.com

Ruby requires that any object passed to raise must be an exception class or object:

2.4.3 :001 > raise Object.new
TypeError: exception class/object expected
        from (irb):1:in `raise'
        from (irb):1
        from /Users/myron/.rvm/rubies/ruby-2.4.3/bin/irb:11:in `<main>'

As such, there’s no way to RSpec to be able to raise an arbitrary object.

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/76d123cf-1fe0-4d88-b0fd-47a856253c22%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

David Shockley

unread,
Apr 11, 2018, 4:34:26 PM4/11/18
to rs...@googlegroups.com
Cool. That makes sense. My current work around is to use:

allow_any_instance_of(Exception).to receive(:my_custom_method_ive_added_to_exception).and_raise

Is there a better solution? Do you think it's possible to write an exception_double and exception_spy methods that build subclasses of Exception that support the double/spy methods directly, or is that unfeasible / a bad idea?



Myron Marston

unread,
Apr 11, 2018, 4:58:54 PM4/11/18
to rs...@googlegroups.com
In general, I recommend that you don't use test doubles in place of value objects, and generally exception types are value objects.  (That is, they carry data, but don't have any meaningful behavior and certainly shouldn't perform any I/O).  Given that, I don't understand why you'd want to use a test double in place of an exception.

The fact that you find yourself wanting to is probably communicating something about your design, and you may want to take a step back to think through why you're trying to use a double in place of an exception.  There's likely an alternate design that will work better.

HTH,
Myron

David Shockley

unread,
Apr 11, 2018, 5:14:35 PM4/11/18
to rs...@googlegroups.com
Thanks for the excellent and informative reply. I'll have to think about that :)

Reply all
Reply to author
Forward
0 new messages