Skip to content

Instantly share code, notes, and snippets.

@jch
Last active December 16, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jch/5453807 to your computer and use it in GitHub Desktop.
Save jch/5453807 to your computer and use it in GitHub Desktop.
Work in progress MiniTest runner allowing multiple setup and teardown hooks around the whole test suite, and individual test cases.
require 'minitest/unit'
module MiniTest
module Hooks
class Runner < MiniTest::Unit
def _run_suite(suite, type)
# TODO: copy over ivars into the testcase instance binding
suite._before_all_blocks.each(&:call)
result = super
suite._after_all_blocks.each(&:call)
result
end
end
module TestCaseInstanceMethods
# Started some stuff with copying over ivars
# def run(runner)
# if !run_once?
# @run = true
# run_once(binding)
# end
# run_always(binding)
# end
# # Determines whether #run_once has already been called.
# #
# # Returns a Boolean.
# def run_once?
# !!@run
# end
end
module TestCaseClassMethods
def before(type = :each, &blk)
case type
when :each
# TODO: rescue exceptions w/ #puke to report errors
add_setup_hook {|test_case| test_case.instance_eval(&blk)}
when :all
_before_all_blocks << blk
end
end
def after(type = :each, &blk)
case type
when :each
# TODO: rescue exceptions w/ #puke to report errors
add_teardown_hook {|test_case| test_case.instance_eval(&blk)}
when :all
_after_all_blocks << blk
end
end
# Internal: saves callbacks to run in the order they are declared
def _before_all_blocks
@@_before_all_blocks ||= []
end
def _after_all_blocks
@@_after_each_blocks ||= []
end
end
end
end
MiniTest::Unit::TestCase.extend(MiniTest::Hooks::TestCaseClassMethods)
MiniTest::Unit.runner = MiniTest::Hooks::Runner.new
$setup_success = $teardown_success = false
class MiniTest::Hooks::RunnerTest < MiniTest::Unit::TestCase
before :all do
puts 'all'
@before_all = true
end
before do
puts 'each'
@before_each = true
end
# after do
# @after_each = true
# end
# after :all do
# @after_all = true
# end
def test_hooks
puts 'hooks'
assert @before_all
assert @before_each
end
def test_another
puts 'run another'
assert @before_each
end
end
# class MiniTest::Hooks::TeardownHooksTest < MiniTest::Unit::TestCase
# def test_teardown_once
# assert $teardown_success # from other test suite
# end
# end
# class MiniTest::Hooks::SetupHooksError < MiniTest::Unit::TestCase
# end
# declare both tests before running to test $teardown_success
MiniTest::Unit.autorun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment