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.
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
ReplyDeleteexpected <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.
Hi Jay,
ReplyDeleteBill here.
'Comment boolean asserts' is probably the entry you were referring to.
Hello Bill,
ReplyDeleteThanks, I've updated the entry.
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?
ReplyDelete