Is there a "safe_stub"?

Right now, #stub stubs a method even if it doesn’t exist. Is there a
way to stub a method on an object, if and only if it already
#responds_to? that method? It would also be good if it raised an
ArgumentError or the like.

Example:

this is how it works now:

- stubs the #bar method even if it doesn’t exist

- always returns ‘baz’

foo.stub(:bar).and_return(‘baz’)

What I’d like is something like this:

raise ArgumentError unless foo.respond_to? :bar

otherwise, behaves as the regular #stub does

foo.stub!(:bar).and_return(‘baz’)

Thoughts?

~ jf

John F.
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: User John Feminella - Stack Overflow

On Jul 27, 2011, at 2:32 PM, John F. wrote:

foo.stub(:bar).and_return(‘baz’)

What I’d like is something like this:

raise ArgumentError unless foo.respond_to? :bar

otherwise, behaves as the regular #stub does

foo.stub!(:bar).and_return(‘baz’)

Thoughts?

This has come up many times before. Please check out
http://groups.google.com/group/rspec/browse_thread/thread/c344c898c278cd2b
and Undefined method stub report · Issue #15 · rspec/rspec-mocks · GitHub to see where the
conversation is at this point.

Apologies for not noticing this – I did search, but I wasn’t sure
exactly how to phrase it. Thanks for the info, David.

~ jf

John F.
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: User John Feminella - Stack Overflow

On Jul 27, 2011, at 5:36 PM, John F. [email protected]
wrote:

Apologies for not noticing this – I did search, but I wasn’t sure
exactly how to phrase it. Thanks for the info, David.

No apology necessary. Just saving myself a bunch of re-typing :slight_smile: Feel
free to weigh in on those threads.

Cheers,
David