Custom assertions are very useful. If you are doing the same verbose test over and over, chances are you could use a custom assertion to do the same job much easier.
So, for starters, lets say you have a basic test that looks like this:
<pre>
data = ['zero','one','two']
assert_equal 3, data.size # Is array size 3?
assert data.size < 50 # Is this array small
assert data.include?(’zero’) # Does it include ‘zero’?
assert_equal 0, ‘0’.to_i # Does this equal 0?
One important thing to understand is when writing custom asserts is that the assert method handles all assertions. All other assertion simply wrap around it. assert takes 2 parameters:
<pre>assert(true_or_false, message_when_false)</pre>
Now lets convert the above into easier to read custom assertions. In test/test_helper.rb we add our assertions inside the class Test::Unit::TestCase.
<pre>
def assert_array_has_3_items(array)
assert 3 == array.size, "Array should have 3 items, but had #{array.size} instead."
end
def assert_small_array(array, threshold = 50)
assert array.size < threshold, “Array is too large, it should be less than #{threshold} items, but instead has #{array.size} items.”
end
def assert_array_includes(array, item)
assert array.include?(item), “Array does not include the item: #{item}”
end
def assert_numeric_zero(value)
assert 0 == value, “Value should be numeric 0, but was #{value}”
end
First of all, note that it was simply a call to assert everytime we execute an assertion. We do a comparison that returns a true or a false, and then we define a message that the console will display when the assertion fails.
Also note that custom assertions are simply method definitions and have all the same rules and flexibility as other methods. For instance, in the assert_small_array above, a default value is specified for the threshold parameter. This means you could easily use assert_small_array(array, 1000) if you decide that 50 is too small for this particular test.
Now lets rewrite our tests to use our new assertions:
<pre>
data = ['zero','one','two']
assert_array_has_3_items data
assert_small_array data
assert assert_array_includes data, ‘zero’
assert_numeric_zero ‘0’.to_i
Custom assertions are quite powerful and will get used quite a bit in larger applications as you will start to noticed some similar tests. Custom assertions allow you to easily refactor those tests so it will perform the test consistently and give a uniform error message that makes sense. Think about adding some if you feel your test methods are getting to complex.