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 ?
A:
Most people don't test the associations, as Rails already has unit tests to make sure those methods work correctly. If you are doing something complex, like involving a proc or something, you might want to explicitly test it. Usually you can do this by just doing
a = Post.new
a.comments << Comment.new
assert a.save
assert a.comments.size == 1
or something akin to that.
Preston Marshall
2010-04-20 06:37:13
I got you partially. I am new to testing. Say I write a unit test to verify that all comments are deleted when related post is deleted. So this is sufficient? Further do i even require to write a unit test to verify a destroy method generated by scaffolding.
alokswain
2010-04-20 06:48:15
A:
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
rspeicher
2010-04-20 07:05:20