Some unit tests can become very similar, up to the point where one might want to put some of the support methods into a module that’s mixed into each test. Some times it might also be a good idea to even create a base class that other unit tests can inherit from. Lets say we do something like the following.

class TypeATest < Test::Unit::TestCase
  def setup
    # Set up some environment.
  end

  def teardown
    # Tear it down again.
  end 
end

class MyTest < TypeATest
  def test_something
    #...
  end
end

The above will however not work. It will give the error “No tests were specified.” since TypeATest did not specify any tests. That can be worked around by e.g. adding a dummy test such as the following.

def test_truth
  assert true
end

That will remove the error, but instead we get another problem: the test statistics will count the dummy method. So if we have one test in TypeATest then it will count as two tests. The same goes for any test that loads the file containing TypeATest.

Luckily there’s a cleaner way to solve it. The error is given by Test::Unit::TestCase#default_test which has that as the only purpose, so instead of using a dummy test we can overwrite the default_test method to do nothing. The statistics are no longer skewed, the only downside is that one no longer gets an error if MyTest doesn’t contain a test. The example above would become the following.

class TypeATest < Test::Unit::TestCase
  def setup
    # Set up some environment.
  end

  def teardown
    # Tear it down again.
  end 

  def default_test; end
end

class MyTest < TypeATest
  def test_something
    #...
  end
end

Sorry, comments are closed for this article.