[rspec-users] Testing Rails Associations

Daniel N has.sox at gmail.com
Fri Jul 6 04:40:52 EDT 2007


On 7/6/07, Daniel N <has.sox at gmail.com> wrote:
>
>
>
> On 7/6/07, David Chelimsky <dchelimsky at gmail.com> wrote:
> > On 7/3/07, Daniel N <has.sox at gmail.com> wrote:
> > > Hi,
> > >
> > >  I'm very new to rspec, so if this is not the right forum please let me
> > > know.
> > >
> > >  I'm starting to spec my models first in an existing rails app, porting
> from
> > > a mix of Test::Unit, and simply_bdd amongst others.
> > >
> > >  I'm at the point where I want to test that certain associations are
> > > present.  What I'm not sure of is should I test the association or the
> > > method and return object.
> > >
> > >  That is, if I wanted to test a has_many should I:
> > >
> > >  Confirm the methods exist, and that the return an array etc
> > >
> > >  OR
> > >
> > >  Check that the model has the named has_many association through it's
> > > reflections.
> > >
> > >  On one hand the second one looks like it will be a bit more robust,
> since
> > > if there is a has_many relationship, then all the associated methods may
> be
> > > used througout the app.  This would put testing in the one place.
> > >
> > >  On the other hand, this would be really testing the implementation of
> the
> > > model rather than it's behaviour.   The behaviour is to call
> > > @article.comments and have an array of comments returned.
> > >
> > >  Any thoughts?
> >
> > I think the jury is still out on this one. Both approaches present
> > problems, and no better approaches have been proposed. I'd say try it
> > both ways and report back on experiences.
> >
> > David
> >
> > >  Cheers
> > >  Daniel
> > >
>
> I went with the second way, testing the association through reflections.
> The reason I did this is that by testing that there is a has_* or belongs_to
> you are really testing the availablity of all the assoicated methods.  Which
> you are then free to use throughout your app.
>
> If you go the other way, you are not in fact testing if a model "has_many"
> since this implies that all has_many methods will be included, not just
> returning and setting an Array.
>
> If your interested I've put up the module that I am using to provide these
> and a couple of other methods on pastie.  This is my first go so please
> don't expect anything spectacular.
>
> http://pastie.caboo.se/76462
>
> Cheers
> Daniel
>

Wow I should really have checked that more thoroughly.  I found many
mistakes in that.

Here is one I've fixed up.

http://pastie.caboo.se/76470

Daniel


More information about the rspec-users mailing list