Checking ActiveRecord Associations in RSpec

Alok Swain picture Alok Swain · Apr 20, 2010 · Viewed 8.7k times · Source

I am learning how to write test cases using Rspec. I have a simple Post Comments Scaffold where a Post can have many Comments. I am testing this using Rspec. How should i go about checking for Post :has_many :comments. Should I stub Post.comments method and then check this with by returning a mock object of array of comment objects? Is testing for AR associations really required ?

Answer

Robert Speicher picture Robert Speicher · Apr 20, 2010

Since ActiveRecord associations should be well-tested by the Rails test suite (and they are), most people don't feel the need to make sure they work -- it's just assumed that they will.

If you want to make sure that your model is using those associations, that's something different, and you're not wrong for wanting to test that. I like to do this using the shoulda gem. It lets you do neat things like this:

describe Post do
  it { should have_many(:comments).dependent(:destroy) }
end