[rspec-users] On Mocks vs Stubs in the context of rSpec

Ben Mabey ben at benmabey.com
Sat Jul 25 02:00:05 EDT 2009

Rick DeNatale wrote:
> On Thu, Jul 23, 2009 at 8:41 PM, Ben Mabey<ben at benmabey.com> wrote:
>> You can, IMO, use a "mock" like a stub and a "stub" like a
>> mock.. Take this for example:
>> describe "#some_method" do
>>  it "delegates to some_obejct" do
>>   some_object = stub('some object', :some_method => "foo")
>>   my_object = MyObject.new(some_object)
>>   my_object.some_method.should == "foo"
>>  end
>> end
>> We are using a stub as a dummy object, and yet our expectation is clearing
>> testing the method call.  So is the above a stub or is it really a mock?  I
>> would say that it is acting like a mock.  I hope that others on the list
>> will correct me if I am wrong making this observation/conclusion.
> Well, I'm not sure.
> There's a difference here.
> The stub simply sets things up so that IF some_object receives
> :some_method it will return 'foo' instead of something else (including
> a method_missing error).
> If the implementation looks like:
> class MyObject
>     def initialize(obj)
>     end
>     def some_method
>        "foo"
>     end
> end
> Then the stub object proves nothing, the example will succeed whether
> it's there or not.
> On the other hand using a mock and setting a message expectation
> asserts something about the implementation of some_method and it's
> relationship to the intialize method.  It's more gray-box than
> black-box.

True, but I think the difference is very small in this case.  In the 
delegation example we want to ensure that the other method is called and 
that it's return value is returned.  Adjusting your implementation 
slightly you could still make the message expectation version pass as 
well but still be a false-positive:

class MyObject
    def initialize(obj)

    def some_method

In both cases another example would be needed to point out the problem- each of which would rely on returning another canned response.  Of course, using triangulation for something small as delegation is just plain silly. :)  FWIW, I would set a message expectation when specifying delegation.  However, to my point if a stub is being used in this manner I think it is crossing the line of being a dummy object and taking on more of a "mock"ish like role.  Perhaps it is going overboard to say that it is being used as a mock, but the intent feels the same in this case IMO.


More information about the rspec-users mailing list