Extending Test::Unit with custom assertions
Test::Unit is great but, of course, it’s designed to work everywhere and so it isn’t tailored to your specific domain. Fortunately though, that’s not a problem since adding your own custom assertions is as easy as creating two methods in your test helper.
Let’s say you have the following class:
class Polly
def is_awesome?
true
end
end
And you wan’t to test whether Polly is awesome, which isn’t something you normally would have to test since I obviously am, but bare with me
So you would do something like this:
class PollyTest < Test::Unit::TestCase
def setup
@polly = Polly.new
end
def test_that_polly_is_awesome
assert @polly.is_awesome?
end
end
Or, you could write a custom assertion to test whether any given object is awesome or not:
def assert_awesome(obj, msg=nil)
msg ||= "Excpected #{obj.inspect} to be awesome"
assert_block msg do
obj.is_awesome?
end
end
def assert_not_awesome(obj, msg=nil)
msg ||= "Excpected #{obj.inspect} not to be awesome"
assert_block msg do
!obj.is_awesome?
end
end
Now you could test awesomeness like this:
def test_that_polly_is_awesome
assert_awesome @polly
end
def test_that_some_other_dude_isnt_awesome
assert_not_awesome @some_other_dude
end
Custom assertions are great for making tests cleaner and easier to read, but don't go crazy with them, testing ones awesomeness, for example, might not be all that usefull
