Rails RSpec Tests for a has_many :through Relationship

Mario Zigliotto picture Mario Zigliotto · Oct 20, 2010 · Viewed 27.1k times · Source

I'm new to testing and rails but i'm trying to get my TDD process down properly.

I was wondering if you use any sort of paradigm for testing has_many :through relationships? (or just has_many in general i suppose).

For example, i find that in my model specs i'm definitely writing simple tests to check both ends of a relationship for relating methods.

ie:

require 'spec_helper'

describe Post do

  before(:each) do
    @attr = { :subject => "f00 Post Subject", :content => "8ar Post Body Content" }
  end

  describe "validations" do
  ...    
  end

  describe "categorized posts" do

    before(:each) do
      @post  = Post.create!(@attr)
    end

    it "should have a categories method" do
      @post.should respond_to(:categories)
    end

  end

end

Then in my categories spec i do the inverse test and check for @category.posts

What else am i missing? thanks!!

Answer

Peter Brown picture Peter Brown · Oct 20, 2010

I would recommend checking out a gem called Shoulda. It has a lot of macros for testing things like relationships and validations.

If all you want is to test that the has_many relationship exists, then you could do the following:

describe Post do
  it { should have_many(:categories) }
end

Or if you're testing a has_many :through, then you'd use this:

describe Post do
  it { should have_many(:categories).through(:other_model) }
end

I find the Shoulda Rdoc page very helpful too.