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
Your test will still pass if the test is coded as:
def test_coded?
assert obj.coded?
However, this test will fail:
def test_coded?
assert_equal true, obj.coded?
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.


  1. On a connected subject, I always use assertEquals rather than assertTrue for my boolean assertions tests in Java and C# (no ruby yet sorry) because I find the

    expected <true>
    but was <false>

    much more explicit than a simple


    Also, I find it easier it refactor and reuse the assertions where i can simply pull the expected boolean value out as a parameter.

  2. Anonymous11:22 AM

    Hi Jay,

    Bill here.

    'Comment boolean asserts' is probably the entry you were referring to.

  3. Anonymous12:46 PM

    Hello Bill,
    Thanks, I've updated the entry.

  4. In C++ you can use a macro to define the assertion so when the assertion fails, you can print out the textual representation of the test. Do you think something similar would be natural enough in Ruby, via an assertion wrapping around eval?


Note: Only a member of this blog may post a comment.