A Ruby Test Framework in One Line
11:17 AM EDT Friday, May 23 2008
Time for a little Friday fun with Ruby. I love Ruby for things like this. I realize this has little practical usage, but the fact that it's possible says a lot about the language. You can build a test "framework" in one line of code in Ruby. Let's say we are going to write a method that take 0 to n arguments and adds them up. So following TDD, we write the tests first:
tests = {
"sum" => 0,
"sum(7)" => 7,
"sum(2, 3)" => 5,
"sum(2, 3, 5)" => 10
}
The tests are defined in a hash where the key is the code to be tested in a string and the value is the expected result. Next we write our implementation:
def sum(*args)
(args || 0).inject(0){|s,e| s+e}
end
And finally, we create and execute our test framework in one line of code:
tests.each{|e,v| puts((r=eval(e))==v ? ". #{e}" : "! #{e} was '#{r}', expected '#{v}'")}
The output looks like this:
. sum
. sum(2, 3, 5)
. sum(7)
. sum(2, 3)
If we change one of our tests to show a failure, you get this:
. sum
. sum(2, 3, 5)
. sum(7)
! sum(2, 3) was '5', expected '8'