Should I write unit tests for my associations?
I haven't found many good resources on how and whether to do the testing. I also see/hear some opinion that it is okay to not test your associations (belongs_to and has_many) as they are already tested in rails. And there is another view that says, if it code you write, it is code you test.
So if you say I should, please tell me few good ways of doing this. Currently, I'm writing tests using Test::Unit and I'm not using Shoulda (I don't have any macros). So for testing each association, I am creating a bunch of objects and then doing asserts on them. Somewhat like this -
For a Post model that has_many comments, my test logic goes this way -
p = Post.create(:title =开发者_运维技巧> 'dummy_title', :content => 'lorem ...')
3.times{ Comment.create(:post_id :=> p.id, :commentor => 'jack')}
assert_equal(3, p.comments.size, "post doesn't have correct no of comments")
To me, testing the association borders on testing the language (or in this case, testing the framework).
I'd reserve it for circumstances where you're doing something nonstandard with the association. For example, if every time you create a comment it changes something in the parent post, test that.
精彩评论