[rspec-users] mock_model

Ashley Moran ashley.moran at patchspace.co.uk
Thu Apr 10 16:55:06 EDT 2008

On 10 Apr 2008, at 18:54, Pat Maddox wrote:
> stub_model, available in RSpec trunk, may be more to your liking.  You
> can read about it at
> http://rubyforge.org/pipermail/rspec-devel/2008-March/004782.html

 From the linked post:
> Also - right now it checks the hash against the model's attributes. If
> the model has a matching attribute it gets assigned, otherwise a stub
> is created. It occurs to me that, with some modification, this *could*
> be used as a bit of an auditing/red-flagging tool. So let's say you do
> this:
>   stub_model(Person, :attrs => {:last_name => 'Name'}, :stubs =>
> {:full_name => 'Full Name'})
> In this case it would fail if the Person model changed :last_name to
> :given_name, for example. I have very mixed feelings about that, and
> might never use it myself, but it would serve to alleviate the fear of
> false positives.

On my last job I extended my client's Factory class so you could  
create either real or mock objects with a stub list. The syntax was  
(uses method missing for the "model_name" bit):
   Factory.mock_model_name(:name => "Fred", :age => 25)

This was against a pure mock (generated from mock_model) so there was  
no issue with attrs vs stubs.  What it did do, however, was something  
like (from memory):
   raise "Useful error message" unless model_class.new.respond_to?(stub)

I also created another version,

which printed to STDERR instead of raising an exception.  (The !  
implying "unsafe" rather than "raises an exception.)  While I was  
using it I found the stub checking REALLY useful (I never used the !  
version myself) - it caught a few cases where I had changed or not  
added a model method.

David: +1 for stub_model, but could you make it autodetect if the stub  
is for an attribute or a method? It would be nice to do away with  
the :attr and :stub distinction.  I have to say, though, I don't see  
the advantage of using a real object as the basis for the mock as long  
as one is used as a sanity check for the stubs (maybe I am missing a  



More information about the rspec-users mailing list