I have a whole load of Test::Unit::TestCase class files. Each one contains a whole load of test_* methods. If I want to run one or two individual test_ methods from a selection of TestCase classes, how do I do it? Simple. Test::Unit has a feature that allows me to create TestSuites from TestCases just by specifying the name of the test when I create an instance of the relevant TestCase class.
I create a file to contain my custom TestSuite (‘sanity_tests.rb‘), and add a require for each TestCase that I contains a test_ method that I want to run as part of this custom TestSuite. I then create a new TestSuite giving it a name. Then, for each test_ method I want to add to my custom TestSuite, I create an instance of its containing TestCase class, passing in a string representation of the test_ method I want to execute. The initialization returns a TestSuite object which is appended to the custom TestSuite that I just created.
Once I’ve done this for every test_ method that I’m interested in, I execute my custom TestSuite and wait for the results! Here’s a code example. The comments should make it clear…
#relevant test::unit requires
require 'test/unit'
require 'test/unit/ui/console/testrunner'
#TestCase classes that contain the methods I want to execute
require 'One/test_one'
require 'Two/test_two'
#create a new empty TestSuite, giving it a name
my_tests = Test::Unit::TestSuite.new("My Special Tests")
#add the test method called 'test_one' defined
#in the TestOne TestCase class to the my_tests
#test suite defined above
my_tests << TestOne.new('test_one')
#add the test method called 'test_me' defined
#in the TestTwo TestCase class to the my_tests
#test suite defined above
my_tests << TestTwo.new('test_me')
#run the suite
Test::Unit::UI::Console::TestRunner.run(my_tests)
And the output is as expected:
Loaded suite My Special Tests
Started
..
Finished in 1.000935 seconds.
2 tests, 2 assertions, 0 failures, 0 errors