5. Hey Test/Unit. Assert This!

By now you’ve caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure things are going as planned.

There are a bunch of different types of assertions you can use. Here’s the complete list of assertions that ship with test/unit. The [msg] is an optional string message you can specify to make your test failure messages clearer. It’s not required.

*assert* ( boolean, [msg] ) ... ensures the object/expression is true

*assert_equal* ( obj1, obj2, [msg] ) ... ensures obj1 obj2 is true @*assert_not_equal* ( obj1, obj2, [msg] )@ ... ensures obj1 obj2 is false

*assert_same* ( obj1, obj2, [msg] ) ... ensures obj1.equal?(obj2) is true

*assert_not_same* ( obj1, obj2, [msg] ) ... ensures obj1.equal?(obj2) is false

*assert_nil* ( obj, [msg] ) ... ensures obj.nil? is true

*assert_not_nil* ( obj, [msg] ) ... ensures obj.nil? is false

*assert_match* ( regexp, string, [msg] ) ... ensures a string matches the regular expression

*assert_no_match* ( regexp, string, [msg] ) ... ensures a string doesn’t matches the regular expression

*assert_in_delta* ( expecting, actual, delta, [msg] ) ... ensures the numbers expecting and actual are within delta of each other

*assert_throws* ( symbol, [msg] ){ block } ... ensures a block throws the symbol

*assert_raises* ( exceptions ){ block } ... ensures a block raises one of the comma-separated exceptions

*assert_nothing_raised* ( exceptions ){ block } ... a block doesn’t raise one of the comma-separated exceptions

*assert_instance_of* ( class, obj, [msg] ) ... ensures obj is the class type

*assert_kind_of* ( class, obj, [msg] ) ... ensures obj is or descends from class

*assert_respond_to* ( obj, symbol, [msg] ) ... ensures obj has a method called symbol

*assert_operator* ( obj1, operator, obj2, [msg] ) ... ensures obj1.operator(obj2) is true

*assert_send* ( array, [msg] ) ... ensures that executing the method listed in array[ 1 ] on the object in array[ 0 ] with the parameters of array[ 2 and up ] is true. This one is weird eh?

*flunk* ( [msg] ) ... ensures failure… like me and high school chemistry exams.

Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that’s exactly what Rails does. It has some specialized assertions to make your life easier.

Creating your own assertions is more of an advanced topic we won’t cover in this tutorial.