Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define common setup and teardown logic for all tests in ruby's Test::Unit::TestCase?

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
like image 255
raphinesse Avatar asked Feb 02 '12 20:02

raphinesse


People also ask

Where will you use setUp () and tearDown () methods?

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 .

What is tearDown in unit testing?

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.

Does tearDown run after every test?

Code in a teardown() block is run upon completion of a test file, even if it exits with an error.


1 Answers

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.

like image 122
raphinesse Avatar answered Sep 22 '22 14:09

raphinesse