Friday, September 08, 2006

Ruby Asserting Equality with True

Bill Caputo wrote a blog entry several months ago stating that he preferred tests that assert equality over tests that simply assert truth. If I remember correctly the main point was that an error message such as 1 expected but was 2 is much more descriptive than false is not true.

I agree with Bill and think it's a great guideline to follow when writing tests. Unfortunately, there are also times when I need to assert truth. These tests usually appear when I need to test a method that should return true or false. In these situations I've found it valuable to use assert_equal instead of assert when programming in Ruby.

The largest reason for this choice is because Ruby treats everything that is not nil or false as true. Therefore, if you are testing the coded? method and you have an implementation error such as:
def coded?
state = :coded
end
Your test will still pass if the test is coded as:
def test_coded?
assert obj.coded?
end
However, this test will fail:
def test_coded?
assert_equal true, obj.coded?
end
Clearly, you should also have a test that verifies that coded? is false; thus, better coverage mitigates this risk. However, I still prefer the assert_equal test implementation because I feel it makes my test suite more robust.
Post a Comment