Assume there are potentially expensive operations to be performed in setup
or teardown
that are same for all tests and whose results doesn't get messed with during test runs. It seems not right to me to have them run before/after every single test.
So is there a preferred way to run setup/teardown code only before the first test is executed and only after the last test ran?
Edit: The particular case I'm working on should test some extensions to Net::FTP and thus establishes a FTP connection and sets up some remote objects for testing:
class TestFTPExtensions < Test::Unit::TestCase
def setup
# Setup connection
@ftp = Net::FTP.new 'localhost', 'anonymous'
@ftp.passive = true
# Create remote test directory
@ftp.mkdir 'dir'
# Create remote test file
path = File.join Dir.tmpdir, 'file'
File.open path, 'w' do |f|
@ftp.put f
end
File.delete path
end
def teardown
@ftp.rmdir 'dir'
@ftp.delete 'file'
@ftp.close
end
# imagine some tests here that don't change/remove any remote objects
end
Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .
When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.
Code in a teardown() block is run upon completion of a test file, even if it exits with an error.
Thanks to Andrew I found an answer to this here on stackoverflow.
However in the course of trying to find an answer I also noticed that in the 1.9.x branch the standard testing framework was switched to MiniTest. So actually I'm using that for testing right now. This answer explains how to achieve the same with MiniTest.
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