Overtesting, Who Cares?
As I indicated in a prior post I’m beginning to wrap my head around Rspec and use it in a new project that I’m working on. I recently came across a post where someone had written something similar to the following, indicating a spec forhas_many and
belongs_to in a model.
context "A Category with fixtures loaded" do
fixtures :listings, :categories
specify "should have many Listings" do
l = categories(:cars).listings
l.should_not be_nil
l.should_not be_empty
l.first.should be_an_instance_of Listing
end
end
One of the comments to the blog post was critical of this approach suggesting that this spec was validating Rails code and that the author should focus only on code that he / she has written. I’ve seen this argument several times in the past and this issue actually came up briefly in the Advanced Rails Training course in Chicago.
While I agree that you shouldn’t be testing Rails code, that’s not what is going on here.
The spec is for the existence of the defined relationships within the model, and that things
are wired up properly to enable accessing the relationship properly within the model. If someone
were to inadvertently remove the has_many method call in the model the spec
would fail, which is exactly the behavior we want.
Secondly, even if we were testing Rails code, I think it’s better to error on the side of overcoverage than to not write tests at all. It is important that developers are not so overwhelmed with the “right” or “wrong” way to do testing that testing is not done at all.
The above code actually comes from a project I’m working on. This blog post aside, if you have recommendations on how it should be done differently, please let me know.
