Rspec'ing Model Associations

Posted on February 27, 2007

How do you go about spec’ing model associations?

There’s an idea on the rspec mailing list.

However, I kind of like using reflect_on_association. Let’s say we have the following model:

class Product < ActiveRecord::Base

  has_and_belongs_to_many :categories
  has_many :images
  has_many :inventories
  belongs_to :designer

end

Then my context and specifications might look like:

context "Product model" do

  specify "should respond to inventories" do
    Product.reflect_on_association(:inventories).should_not_be_nil
  end

  specify "should respond to categories" do
    Product.reflect_on_association(:categories).should_not_be_nil
  end

  specify "should respond to images" do
    Product.reflect_on_association(:images).should_not_be_nil
  end

  specify "should respond to designer" do
    Product.reflect_on_association(:designer).should_not_be_nil
  end
end

This will catch the situation where an association definition is removed or changed.