June 2009
Intermediate to advanced
336 pages
9h 13m
English
A few good habits go a long way when it comes to TDD. We’ll now take a look at some key techniques that help make writing solid and maintainable tests much easier.
A common beginner habit in testing is to create a single example that covers all of the edge cases for a given method. An example of this might be something along these lines:
class VolumeTest < Test::Unit::TestCase
must "compute volume based on length, width, and height" do
# defaults to l=w=h=1
assert_equal 1, volume
#when given 1 arg, set l=x, set w,h = 1
x = 6
assert_equal x, volume(x)
# when given 2 args, set l=x, w=y and h=1
y = 2
assert_equal x*y, volume(x,y)
# when given 3 args, set l=x, w=y and h=z
z = 7
assert_equal x*y*z, volume(x,y,z)
# when given a hash, use :length, :width, :height
assert_equal x*y*z, volume(length: x, width: y, height: z)
end
endThough it is relatively easy to type things out this way, there are some limitations that are worth noting. One of the most obvious issues with this approach is that it isn’t very organized. Compare the previous example to the next, and you’ll see how much easier it is to read things when they are cleanly separated out:
class VolumeTest < Test::Unit::TestCase must "return 1 by default if no arguments are given" do # defaults to l=w=h=1 assert_equal 1, volume end must "set l=x, set w,h = 1 when given 1 numeric argument" do x = 6 assert_equal x, volume(x) end must "set l=x, w=y, and h=1 when given 2 arguments" do x, y = 6, 2 ...
Read now
Unlock full access