Drilling Down into Validation Failure
Rails provides model-level validation, a single entry-point for all your validation needs. If you don’t know about validation, learn. Now. It’ll save you hours and hours of pain and brain-power.
In any case, ActiveRecord provides a valid? method you can call to check if your instance is valid (passes validation). But what if you have multiple fields you’re validating, or some complex piece of validation? How can you find out the exact, precise error?
ActiveRecord also provides an error property, which, among other things, has an invalid? method; it takes a field name, and returns if that field is valid or not.
For example, in Launchpad, we have an Article model; it validates for the presence of the title, and the content fields (among other things). If we create an empty article instance, we expect it to fail validation, and that both these fields are invalid.
Here’s the unit test code that expresses this:
def test_invalid_with_empty_attributes
article = Article.new
assert !article.valid?
assert article.errors.invalid?(:title)
assert article.errors.invalid?(:content)
end
Easy as that. Of course, if you use complex validation by overwriting the validate function, you can probably find cases where all fields pass validation but validation itself fails.
Tags: introductory, launchpad, validation Posted in


Leave a Reply