[rspec-users] a better "should have valid associations"

Craig Demyanovich cdemyanovich at gmail.com
Thu Mar 29 09:03:25 EDT 2007

On Mar 29, 2007, at 5:38 AM, Ashley Moran wrote:

> On 29 Mar 2007, at 09:18, Courtenay wrote:
>> Note: I usually feel that testing associations is really testing the
>> framework, and such code belongs in the framework itself.
> All the fancy details that load and save are part of the framework,
> but you still have to write has_whatever in your model class.  My
> test-code ratio for models is 3.8:1, almost entirely due to copy-and-
> past coding to verify the associations.  I'd love a really expressive
> way of testing associations like "Car.should have_many(:wheels)" or
> "Bull.should have_one(:udder)" or whatever.  But looking at my own
> code it would be hard to factor out a one-size-fits-all expectation,
> especially through associations.

Here's how I'm currently specifying my associations:

context "All campaigns" do

   specify "may have many funds" do
     association = Campaign.reflect_on_association(:funds)
     association.macro.should == :has_many
     association.class_name.should == 'Fund'
     association.options.should == { :foreign_key => 'FK_Campaign' }


context "All funds" do

   specify "may belong to a campaign" do
     association = Fund.reflect_on_association(:campaign)
     association.macro.should == :belongs_to
     association.class_name.should == 'Campaign'
     association.options.should == { :foreign_key => 'FK_Campaign' }


Doing more than this feels like doing too much. However, I'm still a  
bit of a beginner when it comes to Rails. Am I specifying too little?  
Am I missing something?


More information about the rspec-users mailing list