Rails RSpec Tests for a has_many :through Relationship

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)