Global setup and teardown blocks in Test::Unit
What's the best way to hav开发者_开发百科e a setup run before every method in an entire test suite (not just one test class)?
Rspec allows you to define global before and after blocks. Is there a clean comparable way to do this in Test::Unit that doesn't involve mixing a module into each test class?
Assuming you're using Rails. Just add following in your test/test_helper.rb
file.
class ActiveSupport::TestCase
setup :global_setup
def global_setup
#stuff to run before _every_ test.
end
end
Tested on Rails 3.0.9.
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
精彩评论