如何为ruby的Test :: Unit :: TestCase中的所有测试定义通用设置和拆除逻辑?

rap*_*sse 5 ruby installation unit-testing testunit teardown

假设在所有测试中执行setup或者teardown相同的操作可能是昂贵的操作,并且在测试运行期间其结果不会被弄乱.在每次测试之前/之后让它们运行似乎是不对的.

那么有没有一种首选的方法只在第一次测试执行之前运行设置/拆卸代码,并且只在最后一次测试运行之后?

编辑:我正在处理的特定情况应该测试Net :: FTP的一些扩展,从而建立一个FTP连接并设置一些远程对象进行测试:

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
Run Code Online (Sandbox Code Playgroud)

rap*_*sse 5

感谢Andrew,我在stackoverflow上找到了答案。

但是,在尝试寻找答案的过程中,我还注意到在1.9.x分支中,标准测试框架已切换为MiniTest。所以实际上我现在正在使用它进行测试。该答案说明了如何使用MiniTest达到相同的目的。