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

Ben Mabey ben at benmabey.com
Thu Jul 23 20:41:43 EDT 2009

Marcelo de Moraes Serpa wrote:
> Hello list,
> >From what I could see, the lines between mocks and stubs are subtle,
> but the general idea I got is that mocks set expectations and stubs
> are only dummy objects/method calls. What confused me though, is that
> the stub() method is an alias for mock() in
> Spec::Mocks::ExampleMethods. So a stub is a mock?
Yes, no, and maybe so. :p  I agree with your general understanding that 
"mocks set expectations and stubs are only dummy objects/method calls".  
The fact that rspec using the same machinery to provide stubs and mocks 
is really inconsequential because the deciding factor of what they are 
is how you use them.  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"

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.   Likewise we could use a mock as a dummy object 
and never set any expectations on it and it would be acting like a 
stub.  Even though stub and mock is the same in RSpec you should still 
use the correct name when using them.

> Also, another thing that is confusing: You have stub and stub! methods
> in the Spec::Mocks::Methods namespace, what is the difference between
> Spec::Mocks::ExampleMethods#stub and Spec::Mocks::Methods#stub ?

Spec::Mocks::ExampleMethods are the methods that you can call during the course of a code example.  So when you say stub("something") the method in Spec::Mocks::ExampleMethods gets called and returns you a stub.  Now, that stub object now has it's own #stub method which lives on Spec::Mocks::Methods#stub.  That call will stub out the provided method and return value... So my_stub.stub(:foo, "bar"), however that is aliased from #stub! which is used most often.  This is all from memory so I could be wrong but that is the general gist of it.


More information about the rspec-users mailing list