[rspec-users] Mocking and stubbing model relationships
matt at mattwynne.net
Tue Nov 18 03:43:20 EST 2008
On 18 Nov 2008, at 05:41, Nick Hoffman wrote:
> Before writing specs for a one-to-many relationship between two
> models, I did some research and found that some people were creating
> proxy mocks, and others were using Matthew Heidemann's
> #stub_association! (which essentially does that for, but in a nice,
> DRY way):
> Are those two methods currently the accepted "best practice" for
> mocking and stubbing calls such like these?:
I don't know about any "best practice". In the realm of TDD vs
ActiveRecord Associations, you're looking at something more like
"least-worst" practice, IMO. The way the AssociationCollections behave
is pretty complex and difficult to simulate with a simple mock or two.
I started out trying to stay 'pure' and not touch the database, but
TBH, these days I've given up the fight and mostly just throw a few
records in a database table - that way you can actually specify the
behaviour you want rather than the gory implementation details.
As you can probably tell by my grumbling, this is one of my least
favourite bits of working on rails.
> @properties = @user.properties
> @property = @user.properties.new
> @property = @user.properties.find_by_id params[:id]
Saying that, it is often still reasonable, I think, to fake an
association proxy collection using an array that's patched with a few
extra methods. We have a helper method in the Songkick spec code
that's called something like FakeCollection, which subclasses array
and has a few helpful methods to make it look enough like an
association collection to make the specs run OK.
More information about the rspec-users