views:

40

answers:

2

I'm using Test::Unit::TestCase to write some unit tests. Currently, I have a setup function that moves and modifies some fixture files and folders on disk. (This is a necessary evil at the moment.) If a test crashes, the teardown method doesn't get called, leaving files and folders in the way. The next time I run a test, it complains that such-and-such a folder already exists (Errno::EEXIST), making me have to stop and get rid of the left-over files.

How do I ensure that teardown is always run? (ensure is the same idea as finally in some other languages.)

+3  A: 

What about making your setup() do some cleanup so that it works even if the file still exists ?

philippe
Yep, make a clearup routine and have teardown and setup both call it.
Shadowfirebird
That's not a bad idea. I'll try that out.
Benjamin Oakes
This seems to be working pretty well. Making sure that `cleanup` doesn't get called twice erroneously is a little bit of a pain, but it works just fine.
Benjamin Oakes
A: 

How about adding an on-exit hook in setup, then removing it in teardown:

class MyTestCase < Test::Unit::TestCase

  def clean_up!
    ...
  end

  def setup
    at_exit do
      unless @cleaned_up
        clean_up!
      end
    end
  end

  def teardown
    clean_up!
    @cleaned_up = true
  end

end
James A. Rosen