From: jweirich@... Date: 2001-08-10T11:29:07+09:00 Subject: [ruby-talk:19473] Re: RubyUnit: Avoid running setup for every test? >>>>> "Armin" == Armin Roehrl writes: Armin> I'm using Rubyunit on code where I would like to have setup Armin> executed only once and not for every test. Why? The setup Armin> requires about 30 minutes, but its required to have Armin> executed once for the tests. Armin> Is there an easy way of doing that? Armin> (Apart from modifying run_bare of class TestCase (testcase.rb) This is how I do it ... First a little background on how I setup my unit tests. Every file containing unit tests registers the tests to be run in a TestSuite object assigned to a global variable named $last_suite. A typical test file might look like this ... -- Example Test File ------------------------------------------------- $last_suite = RUNIT::TestSuite.new class TestSample < RUNIT::TestCase # ... end $last_suite.add_test(TestSample.suite) class TestSomethingElse < RUNIT::TestCase # ... end $last_suite.add_test(TestSomethingElse.suite) if __FILE__ == $0 then RUNIT::CUI::TestRunner.run ($last_suite) end ---------------------------------------------------------------------- It can be run standalone, or with a separate test loader that scans a directory for test files, loads the file and uses the $last_suite variable to get a list of tests from the file that was just loaded. Recently I wrote some unit tests for the Ruby DBI project. I wanted to setup the database once at the beginning of the test run, and then tear down when all the tests were done. I wrote a wrapper class like the following and put it at the end of the test file. ---------------------------------------------------------------------- class TestWrapper < RUNIT::TestCase def initialize(suite) @test_suite = suite end def setup # Stuff to do before all tests. end def teardown # Stuff to do when all tests are done end def run(test_result) setup @test_suite.run(test_result) teardown end end $last_suite = DbiWrapper.new($last_suite) ---------------------------------------------------------------------- The wrapper class remembers the list of classes in the current $last_suite variable. It then replaces the suite with itself. The TestWrapper class is run, it will do its own setup once, invoke all the tests it remembered internally, and then do its onetime tear down. -- -- Jim Weirich jweirich@one.net http://w3.one.net/~jweirich --------------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)