I'm struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby's framework, I must instead write:
class MyTest < Test::Unit::TestCase def setup end def test_1 end def test_1 end end
But setup and teardown run for every invocation of a test_* method. This is exactly what I don't want. Rather, I want a setup method that runs just once for the whole class. But I can't seem to write my own initialize() without breaking TestCase's initialize.
Is that possible? Or am I making this hopelessly complicated?
Structuring and Organizing Tests Tests for a particular unit of code are grouped together into a test case, which is a subclass of Test::Unit::TestCase. Assertions are gathered in tests, member functions for the test case whose names start with test_.
As mentioned in Hal Fulton's book "The Ruby Way". He overrides the self.suite method of Test::Unit which allows the test cases in a class to run as a suite.
def self.suite mysuite = super def mysuite.run(*args) MyTest.startup() super MyTest.shutdown() end mysuite end
Here is an example:
class MyTest < Test::Unit::TestCase class << self def startup puts 'runs only once at start' end def shutdown puts 'runs only once at end' end def suite mysuite = super def mysuite.run(*args) MyTest.startup() super MyTest.shutdown() end mysuite end end def setup puts 'runs before each test' end def teardown puts 'runs after each test' end def test_stuff assert(true) end end
FINALLY, test-unit has this implemented! Woot! If you are using v 2.5.2 or later, you can just use this:
Test::Unit.at_start do # initialization stuff here end
This will run once when you start your tests off. There are also callbacks which run at the beginning of each test case (startup), in addition to the ones that run before every test (setup).
http://test-unit.rubyforge.org/test-unit/en/Test/Unit.html#at_start-class_method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With