views:

347

answers:

4

Is it necessary to unit test ActiveRecord validations or they are well-tested already and hence reliable enough?

+8  A: 

Validations per se should be trustable, but you may want to check if the validation is present.

Put in other words, a good way to test something is as if it were a black box, abstracting the tests from the implementation, so for instance you may have a test that checks that a person model can't be saved without a name, but don't care about how the Person class performs that validation.

krusty.ar
+4  A: 

It should be sufficient to accept that libraries such as ActiveRecord are better-tested by the developers than they ever will be by you: for them it's a primary concern, for you it's at best tangential.

That's not to say there won't be bugs - I found a small one the MS SQL Server adapter once a long time ago - but the kind of test you're likely to be implementing is highly unlikely to expose them as they're most likely to be edge cases. If you do find a bug, of course, it's probably very helpful if you report it with a test case that exposes it!

I would only test ActiveRecord internals if I was seeking to understand better a particular aspect that the library implements. I would not include those exploratory tests in any application project, since they're not really relevant to the project.

In general, you should write tests for code that you write yourself: if you live or try to live in a TDD world, the tests should be written before. If your models have validation rules then you should almost certainly write tests to ensure the rules are present. In most cases, the tests will be trivial, but they'll really be useful if a line inadvertently gets deleted some time in the future...

Mike Woodhouse
+3  A: 

As Mike wrote, at the very least you should test that the validation exists. It's just a bit of double-entry accounting (sanity check) that is easy enough to do.

Depending on the situation, you should also test that your model is valid or invalid under particular circumstances. For example if your field requires a certain format, then test the example formats that are valid and those that aren't. It's much easier to see what this means by reading a few examples in your tests:

class Person < ActiveRecord::Base
  validates_format_of :email,
      :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end

Yes, the validations are well-tested and reliable enough. But your correct use of the validations is what you want to verify.

Andrew Vit
A: 

As a side note, Ryan Bigg's blog post has_and_belongs_to_many double insert mentions someone encountering a bug in ActiveRecord (not validation related, though). As he points out, don't assume Rails can't possibly have a bug, because we know there are 900 open tickets for Rails.

But yes, the main reason you'd write a test is to check that your use of ActiveRecord is correct.

Andrew Grimm