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.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Testing and tagged , , . Bookmark the permalink.

One Response to Drilling Down into Validation Failure

  1. Pingback: User links about "validation" on iLinkShare