Forcing some code to run at the end of tests

I don’t mean to beat a dead horse, but i think i’ve come up with a
viable solution for this that doesn’t involve manualy launching every
test through TestRunner, or stratigicaly placing BEGIN & END blocks.

All you really need to to is extend Test::Unit::TestCase and
programaticly add functionality for a startup() method (to run before
all testcases) and a close() method to run after everything.

In the class below i’ve overloaded #run to check if a startup methods
been run, and if not launch it before running anything. I’ve also made
use of the default_test (which curiously always runs after? - this might
be changed later on so i won’t count in it working forever), to launch
the close method.

require ‘test/unit/assertions’
require ‘test/unit/failure’
require ‘test/unit/error’
require ‘test/unit/assertionfailederror’
require ‘test/unit/testcase’

module Test
module Unit
class BetterTestCase < TestCase

  # startup flag
  @@startup_flag = true

  # Overloaded from Test::Unit::TestCase
  def run(result)
    if(@@startup_flag)
      begin
        startup
      rescue
        #ignore
      ensure
        @@startup_flag = false
      end
    end

    yield(STARTED, name)
    @_result = result
    begin
      setup
      __send__(@method_name)
    rescue AssertionFailedError => e
      add_failure(e.message, e.backtrace)
    rescue StandardError, ScriptError
      add_error($!)
    ensure
      begin
        teardown
      rescue AssertionFailedError => e
        add_failure(e.message, e.backtrace)
      rescue StandardError, ScriptError
        add_error($!)
      end
    end
    result.add_run
    yield(FINISHED, name)
  end

  # Called once before any test method runs. Can be used to
  # setup script-wide variables and conditions.
  def startup
  end

  # Called once after all test methods have ran. Can be used to
  # cleaup the environment after completion of the test methods.
  def close
  end

  #overload default_test, actualy runs last?
  def default_test
    begin
      close
    rescue
      #noop
    end
  end
end

end
end

After all this you can build your Test::Unit::TestCases by extending
that instead, and using startup and close the same way you would use
setup & teardown. handy eh?

example test case with startup and close methods:

require ‘test/unit’
require ‘better_test_case’

class ExampleTest < BetterTestCase

def startup
#do somthing once before any tests are run
end

def close
#do somthing after all tests are run
end

def test_0010_somthing
#test somthing…
end

end