[rspec-users] Testing Rails Associations
has.sox at gmail.com
Fri Jul 6 03:49:52 EDT 2007
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
> > 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,
> > if there is a has_many relationship, then all the associated methods may
> > used througout the app. This would put testing in the one place.
> > On the other hand, this would be really testing the implementation of
> > 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.
> > 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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the rspec-users