Plugins - Testcase - Setup and Teardown with Blocks
Add to favoritesThe current implementation of setup and teardown by Test::Unit and Rails only allow the setup method to be overridden once. In the following example, only the setup and teardown methods in PersonTest will be executed:
class Test::Unit::TestCase
# This is overridden by the subclass and will not be called
def setup
end
# This is overridden by the subclass and will not be called
def teardown
end
end
class PersonTest < Test::Unit::TestCase
# This overrides the method in the superclass
def setup
end
# This overrides the method in the superclass
def teardown
end
# Only the setup and teardown methods in this class will be called
def test_name
end
end
This behaviour is quite standard in object oriented programming, but in the case of Test::Unit it would be nice to be able to define multiple setup and teardown methods.
This implementation of setup and teardown makes use of blocks, rather than full methods. The above example becomes:
class Test::Unit::TestCase
setup do
end
teardown do
end
end
class PersonTest < Test::Unit::TestCase
setup do
end
teardown do
end
def test_name
end
end
Both setup and teardown can be called in class definitions as many times as required and, during testing, are executed in the order they are defined.
Existing code will continue to work as before. Code containing setup and teardown methods do not have to be converted to block format although it is recommended for consistency.
Resources
Installation
- script/plugin install http://svn.viney.net.nz/things/rails/plugins/testcase_setup_and_teardown_with_blocks
http://svn.viney.net.nz/things/rails/plugins/testcase_setup_and_teardown_with_blocks/
Rails' (MIT)
Testing

This breaks transactional tests where fixtures are not specified. The Rails behaviour when usetransactionfixtures == true is to run each test within a transaction regardless of whether any fixtures have been specified or not. This plugin breaks this, when no fixtures are specified and tests are not run in a transaction which can cause your test database state to become out of whack.
You can fix this by removing the unless ... after the calls to setupwithfixtures and teardownwithfixtures.