Powered By BlogNow - Get Your Free Blog

I have moved!

My new blog is at lindsaar.net

All the old content will stay here though. But check out the new blog

¿ 22/7/2007 - How to test model associations in RSpec

Graeme Nelson has blogged about a great way to check all your model associations inside of RSpec.

Basically, the method you use:

Model.reflect_on_association(:association_model_name).should_not be_nil

This works using ActiveRecord's method "reflect_on_association" which returns the Class that the association belongs to/ has many of or whatever else :)

You can put a whole lot of these together and quickly and effectively test all the associations that you write into your models.

This keeps with the good testing practice of "Only test the code that you write".  As, when you set up an association, really, the only code you write is the "belongs_to" and "has_many's" or whatever else.

So why would you test that ActiveRecord handles this for you?  You wouldn't.  It would be a waste of time.  Better is to just test the association, which, from the point of view of what YOU wrote, is just the belongs_to has_many relationship and the model / class definitions.

blogLater

Mikel
Post A Comment! :: Send to a Friend!

¿ 22/7/2007 - Untitled Comment

Posted by Evgeny
How about:

association = User.reflect_on_association(:location)
association.macro.should == :belongs_to
association.class_name.should == 'Location'
association.options.should == { :counter_cache => true }

any way to spec all that (location + counter_cache) in one line?

Permanent Link

¿ 22/7/2007 - Reflection one liner

Posted by mikel
@Evgeny

Short answer, no.

Only ever so slightly longer answer, ABSOLUTELY! :)

Go to my newer post with nicely formated code in it.

http://www.blognow.com.au/q/67540/Reflect_on_association_one_liner_to_check_association_details.html

Mikel


Edited by mikel on 22/7/2007 at 2:59 AM
Permanent Link

¿ 23/7/2007 - nicely formatter code

Posted by Evgeny
I just fixed up my wordpress to format code properly too. Didn't think it would be so complex. Take a look http://blog.kesor.net - perhaps you will know some answers regarding my latest puzzle as well. :)
Permanent Link

About Me

AKA Raasdnil, this site is about web coding, hosting and all other matters that relate to this... especially Ruby on Rails!

Links