Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you directly stub! mock objects?

Tags:

mocking

rspec

I might be missing something completely obvious here, but why do I have to do this:

setup do
  @person = mock("person")
  @person.stub!(:name).and_return("david")
end

Instead of

@person = mock("person").stub!(:name).and_return("david")

What is mock("string") returning that doesn't allow it to be stubbed versus allowing @person to be stubbed? Is mock not returning an object (perhaps just modifying some internal hash table of mock'ed out functions and then returning a separate object?

like image 459
David Avatar asked Nov 19 '25 22:11

David


1 Answers

Because the and_return call doesn't return the stub object. mock does.

First, in order to have a mock object to work with, you have to create the actual mock object and assign it to a variable. When you call mock("person").stub!... the mock object is lost in the call chain. Your chained version would only work if and_return returned the original mock object.

like image 193
Peter Lillevold Avatar answered Nov 22 '25 03:11

Peter Lillevold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!