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

Rick DeNatale rick.denatale at gmail.com
Fri Jul 24 20:27:34 EDT 2009


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.
-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale


More information about the rspec-users mailing list