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

Ben Mabey ben at benmabey.com
Fri Jul 24 15:41:40 EDT 2009

Marcelo de Moraes Serpa wrote:
> Thanks David and Ben for the comprehensive replies! I really appreciate it :)
> These wikipedia articles helped me to understand on the more conceptual level:
> http://en.wikipedia.org/wiki/Method_stub
> http://en.wikipedia.org/wiki/Mock_object
> So, if I understand it right -- Stub is for methods and Mocks are for
> roles (or, in the technical-level -- objects).
> In the context of rSpec/rSpec-Rails, however,  the API makes it
> confusing, to be honest. Being able to create a Mock with
> Spec::Mocks:Mock with Spec::Mocks::ExampleMethods# confuses me.
Hmm.. I can see your point as far as where the methods live being 
confusing.  Reading about stub method in the RDoc pages for mock methods 
does seem odd.  The reason, as David, pointed out is really more due to 
reducing code duplication between the two.  Any suggestions on making it 

> The same applies for stub_model() and mock_model(). I know that
> mock_model is a convenience method that can be used to create an
> object with an API similar to ActiveRecord::Base's. The API says
> stub_model is basically the same, but prevents the object from
> accessing the database. Ok, but why attaching these concepts to Stub?
> Is this the right name to use for this method? (Stub == mock object
> that is not allowed to access the database?).
I think you raise a good question whether or not stub_model is a best 
name for the functionality it provides.  I think stub_model is really 
called a partial stub.. or partial mock.  Hmm.. I'm not quite sure what 
the correct name is.  But basically, as you said, it is the real object 
but is not allowed to touch the DB.  So it is there for performance 
reasons mostly.  mock_model however gives you a dummy object with some 
predefined stubbed methods that you typically want for an AR object 
(i.e. #id).  However, it is very true that in many cases you will be 
using this "mock_model" as a stub.  I can see how having stub_model can 
cause confusion...

Perhaps, a better API would be to alias stub_model to mock_model (this 
would be more aligned with the #mock and #stub API) and then have a 
partial_stub_model or stub_model(Model, :partial => true)?   Changing it 
now I'm sure would make some people upset but it could be done with 
deprecation warnings if it is causing that much confusion... This would 
really be David's call to make and I'm guessing he had some good reasons 
for making the decision he did in the first place.

> And there's the  Spec::Mocks::Methods#stub method, which is the one
> that reflects the concept that "the Stub is a dummy method".

Again, this is due to the implementation..  I see your point, but I 
don't know if the typical user really cares where it lives.  Perhaps a 
little explanation in the RDoc would be sufficient to avoid confusion?


More information about the rspec-users mailing list