Friday, December 22, 2006

Pages 151-2: Organizing and Running Tests - Where to put tests


Listen to this article.

Value: Average

Level: Normal

Summary:
If you run a test case from the command line, Test::Unit is clever enough to notice that there's no main program, so it collects up all the test case classes and runs each in turn. From the command line you can also run just a particular method. You should create a test/ directory where to place all your test source files. This directory is then placed parallel to the lib/ directory containing the code you're developing. This works well as a way of organizing files but leaves you with a small problem: how do you tell Ruby where to find the library files to test ? At the front of your test code (for
example in test_roman.rb), add the following line:

$:.unshift File.join(File.dirname(__FILE__), "..", "lib")

This magic works because the test code is in a known location relative to the code being
tested. It starts by working out the name of the directory from which the test file is run and then constructing the path to the files under test. This directory is then prepended to the load path (the variable $:). From then on, code such as require 'roman' will search the library being tested first.

There are worse ways to achieve this goal: you could build the path into require statements in the test and run the tests from the test/ subdirectory, but if the source file to be tested requires other source files, they won't be found in Ruby's $LOAD_PATH. You could also run the tests from the directory containing the library being tested (% ruby ../test/test_roman.rb). Because the current directory is in the load path, the test code will be able to find it, but this approach will obviously break down if you run the test from somewhere else in your system.

Memo: Always tell your tests where to find the source code to be tested.

Reported errata (at 10/17/06 14:17:18 PDT): 1
* Erratum #1945 is a minor typo.

Errata I found: 0

My suggestions to the author: 0

Doubts: 1
*I didn't understand this sentence: "A second, less immediate problem is that we won't be able to use these same tests to test our classes once installed on a target system, as then they'll be referenced simply using require 'roman'."

0 Comments:

Post a Comment

<< Home