[rspec-devel] stub_model

Adam Williams adam at thewilliams.ws
Tue Mar 18 10:29:59 EDT 2008

I, for one, would find this kind of thing useful. I typically create  
an instance and set id, stubbing or mocking specific methods. I  
believe stubbing and mocking aren't about never using a model's  
behavior as much as it's about controlling /some/ of it. This would  
reduce the number of lines I have to type, and provide the extra  
assurance that I'm not accidentally going to the database.

+1, barring any unforeseen pains in the rear


On Mar 18, 2008, at 9:10 AM, David Chelimsky wrote:

> Hi all,
> Over the last couple of years I've read a ton of mail from users
> concerned with false positives coming from stubbing/mocking methods
> that don't exist. I recently added a stub_model method for
> rspec_on_rails (not yet released, available in git) which I think
> mitigates this a bit. It is still in development and subject to
> change, but here's how it works now.
> It looks a lot like mock_model.
>  stub_model(Person, :name => 'David')
> But it works in a fundamentally different way: FIrst, it creates a
> real instance (which means you have to create the model to use it). It
> assigns it an id by default, but you can set :id => nil if you want it
> to behave like a new record. It overrides new_record? so that it
> behaves as you would expect (false if there is an id, true if not). It
> also overrides #connection, raising an error if there is any attempt
> to access the database. This gives you the db isolation you get from
> mock_model, but with a real object. Kind of like unit_record, but on
> an instance by instance basis.
> I've been using this for a few weeks now (just introduced it to the
> rspec code base a week or so ago) and I'm finding it very useful. I'm
> thinking of changing the generated rails specs to use stub_model
> instead of mock_model, and I'd be curious to hear your thoughts about
> this.
> 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.
> Thoughts?
> Cheers,
> David
> _______________________________________________
> rspec-devel mailing list
> rspec-devel at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-devel

More information about the rspec-devel mailing list