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
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
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
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?Your test will still pass if the test is coded as:
state = :coded
end
def test_coded?However, this test will fail:
assert obj.coded?
end
def test_coded?Clearly, you should also have a test that verifies that
assert_equal true, obj.coded?
end
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.
Comments:
<< Home
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
AssertionException.
Also, I find it easier it refactor and reuse the assertions where i can simply pull the expected boolean value out as a parameter.
expected <true>
but was <false>
much more explicit than a simple
AssertionException.
Also, I find it easier it refactor and reuse the assertions where i can simply pull the expected boolean value out as a parameter.
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?
Post a Comment
<< Home




