You could just patch Test::Unit::TestCase
and define a setup
method:
class Test::Unit::TestCase
def setup
puts 'in setup'
end
end
And your subclasses would just use this by default:
class FooTest < Test::Unit::TestCase
def test_truth
assert true
end
end
class BarTest < Test::Unit::TestCase
def test_truth
assert true
end
end
If a test case needed to have its own setup, you would need to call super
first to ensure that the global setup runs:
class BazTest < Test::Unit::TestCase
def setup
super
puts 'custom setup'
end
def test_truth
assert true
end
end
Is having a global setup really something you need to do, or would it be helpful to have a helper method defined on Test::Unit::TestCase
and call that in the tests that need it? The helper method approach is something that I find beneficial on my projects – the setup state and intention is clearer in each individual test and I don't need to jump around to find some "hidden" setup method. Quite often, a global setup is a code smell indicating that you need to rethink part of your design, but YMMV.
Update
Since you're using ActiveSupport, here's a first stab at something that won't require a call to super
each time you define a setup
method in your test case. I don't know how valuable it is, since it requires a call to a different method and any developer can just define their own setup
method in the test case that will invalidate this change. Here it is:
require 'rubygems'
require 'test/unit'
require 'active_support'
require 'active_support/test_case'
class ActiveSupport::TestCase
def setup_with_global
puts 'In Global setup'
setup_without_global
end
alias_method_chain :setup, :global
end
class FooTest < ActiveSupport::TestCase
def setup_without_global
puts 'In Local setup'
end
def test_truth
assert true
end
end