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 abo
Testing associations is good practice generally, especially in an environment where TDD is highly regarded- other developers will often look to your specs before looking at the corresponding code. Testing associations makes sure that your spec file most accurately reflects your code.
Two ways you can test associations:
With FactoryGirl:
expect { FactoryGirl.create(:post).comments }.to_not raise_error
This is a relatively superficial test that will, with a factory like:
factory :post do
title { "Top 10 Reasons why Antelope are Nosy Creatures" }
end
return you a NoMethodError if your model lacks a has_many
association with comments.
You can use the ActiveRecord #reflect_on_association method to take a more in-depth look at your association. For instance, with a more complex association:
class Post
has_many :comments, through: :user_comments, source: :commentary
end
You can take a deeper look into your association:
reflection = Post.reflect_on_association(:comment)
reflection.macro.should eq :has_many
reflection.options[:through].should eq :user_comments
reflection.options[:source].should eq :commentary
and test on whatever options or conditions are relevant.