16.1. Testing with Test::Unit

The “standard” way to do unit testing in Ruby is with Nathaniel Talbott’s Test::Unit. This has been distributed with Ruby since 2001.

The Test::Unit library uses reflection to analyze your test code. When you subclass the Test::Unit::TestCase class, any methods named starting with test are executed as test code.

require 'test/unit'

class TC_MyTest < Test::Unit::TestCase
  def test_001
    # ...
  end
  def test_002
    # ...
  end
  # ...
end

The methods do not have to be numbered as shown. That tends to be my personal convention, but there are certainly others.

It is inadvisable, arguably incorrect, for the behavior of the tests to rely on the order in which they are run. However, Test::Unit does in fact run them in alphabetical ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.