Better Assertions
Published 5 July 07 by Justin French
You write tests for your models, right? Of course. You probably have quick sanity checks all over your tests like this:
assert u.valid?
And when that assertion is false, you get this ultra-helpful error message:
<false> is not true.
Uh-huh. Awesome, thanks. WTF?
So then you go back into your code and add in a few lines to debug just before the assertion:
u.valid?
puts u.errors.full_messages.join("\n")
assert u.valid?
Waste of time, totally boring, don’t do it. Test::Unit’s assert (and most of the other assertions you see used in Rails) can accept a message when the assertion doesn’t pass. So replace the awful waste of time hack above with this from day one:
assert u.valid?, u.errors.full_messages.join("\n")
When the record is not valid, the assertion will print the error messages along with the standard <false> is not true. But I’m telling you stuff that you don’t really need to know, because the Rails framework has already wrapped up this pattern as a simple assertion:
assert_valid(some_record)
So I guess my point is this… when you’re writing tests, make sure you provide some sort of useful error message, or an inspection of the objection or something with your assertion so that you spend less time debugging.
Further, if you find yourself doing the same stuff over and over, check out the Rails documentation and see if someone’s wrapped up the pattern as a helper or method. If they haven’t write your own and share it with the world.
Before you go…
Here’s some links to my most popular posts: