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

1

8

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
Catholic answered 2/2, 2012 at 20:21 Comment(4)
Depends on what that setup code does. If it adds things to a database, then a fixture/factory is the way to go - at least that's one example - you'd need to be more specific about what actions you're taking. It's also possible that you're tests are doing something outside their actual scope (for example, establishing a connection to an external API), and if it's a case similar to that, you should use mocks, stubs, etc. to simulate the stuff that's outside of what you're actually testing.Amigo
@normalocity I added information on my specific scenario. Still, I can imagine a lot of different scenarios where something like a common setup would come in even more handy. Regarding fixtures, factories, mocks and stubs: it would be helpful if you could come up with some links on these topics so I know what you're talking about ^^Catholic
I think this question has been asked before. You may be able to find it by browsing questions tagged "testunit".Cannae
factory_girl (github.com/thoughtbot/factory_girl) will help you by creating objects in a database on the fly, related techniques will tell you about mocks and stubs (just search for "ruby mocks and stubs" and you'll get what you needAmigo
C
7

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.

Catholic answered 9/2, 2012 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.