Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>That's how it's supposed to work!</p> <p>Each test should be completely isolated from the rest, so the <code>setup</code> and <code>tear_down</code> methods are executed once for every test-case. There are cases, however, when you might want more control over the execution flow. Then you can group the test-cases in <em>suites</em>.</p> <p>In your case you could write something like the following:</p> <pre><code>require 'test/unit' require 'test/unit/ui/console/testrunner' class TestDecorator &lt; Test::Unit::TestSuite def initialize(test_case_class) super self &lt;&lt; test_case_class.suite end def run(result, &amp;progress_block) setup_suite begin super(result, &amp;progress_block) ensure tear_down_suite end end end class MyTestCase &lt; Test::Unit::TestCase def test_1 puts "test_1" assert_equal(1, 1) end def test_2 puts "test_2" assert_equal(2, 2) end end class MySuite &lt; TestDecorator def setup_suite puts "setup_suite" end def tear_down_suite puts "tear_down_suite" end end Test::Unit::UI::Console::TestRunner.run(MySuite.new(MyTestCase)) </code></pre> <p>The <code>TestDecorator</code> defines a special suite which provides a <code>setup</code> and <code>tear_down</code> method which run only once before and after the running of the set of test-cases it contains.</p> <p>The drawback of this is that you need to tell <em>Test::Unit</em> how to run the tests in the unit. In the event your unit contains many test-cases and you need a decorator for only one of them you'll need something like this:</p> <pre><code>require 'test/unit' require 'test/unit/ui/console/testrunner' class TestDecorator &lt; Test::Unit::TestSuite def initialize(test_case_class) super self &lt;&lt; test_case_class.suite end def run(result, &amp;progress_block) setup_suite begin super(result, &amp;progress_block) ensure tear_down_suite end end end class MyTestCase &lt; Test::Unit::TestCase def test_1 puts "test_1" assert_equal(1, 1) end def test_2 puts "test_2" assert_equal(2, 2) end end class MySuite &lt; TestDecorator def setup_suite puts "setup_suite" end def tear_down_suite puts "tear_down_suite" end end class AnotherTestCase &lt; Test::Unit::TestCase def test_a puts "test_a" assert_equal("a", "a") end end class Tests def self.suite suite = Test::Unit::TestSuite.new suite &lt;&lt; MySuite.new(MyTestCase) suite &lt;&lt; AnotherTestCase.suite suite end end Test::Unit::UI::Console::TestRunner.run(Tests.suite) </code></pre> <p>The <a href="http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html" rel="noreferrer"><em>Test::Unit</em> documentation</a> documentation provides a good explanation on how suites work.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload