Class: TestTempFileHelper::TempFileHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/test_temp_file_helper.rb

Overview

Automatically generates and cleans up temporary files in automated tests.

The temporary directory containing all generated files and directories is set by the first of these items which is not nil:

  • the tmp_dir argument to TempFileHelper.new

  • the TEST_TMPDIR environment variable

  • Dir.mktmpdir

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tmp_dir: nil) ⇒ TempFileHelper

Returns a new instance of TempFileHelper.

Parameters:

  • tmpdir (String)

    (optional) if set, determines the temp dir



34
35
36
# File 'lib/test_temp_file_helper.rb', line 34

def initialize(tmp_dir: nil)
  @tmpdir = tmp_dir || ENV['TEST_TMPDIR'] || Dir.mktmpdir
end

Instance Attribute Details

#tmpdirObject

Returns the value of attribute tmpdir.



31
32
33
# File 'lib/test_temp_file_helper.rb', line 31

def tmpdir
  @tmpdir
end

Instance Method Details

#mkdir(relative_path) ⇒ String

Creates a temporary test directory relative to TEST_TMPDIR.

Parameters:

  • relative_path (String)

    directory to create

Returns:

  • (String)

    File.join(@tmpdir, relative_path)



41
42
43
44
45
# File 'lib/test_temp_file_helper.rb', line 41

def mkdir(relative_path)
  new_dir = File.join self.tmpdir, relative_path
  FileUtils.mkdir_p new_dir
  new_dir
end

#mkfile(relative_path, content: '') ⇒ String

Creates a temporary file relative to TEST_TMPDIR.

Parameters:

  • relative_path (String)

    file to create

  • content (String) (defaults to: '')

    (optional) content to include in the file

Returns:

  • (String)

    File.join(@tmpdir, relative_path)



51
52
53
54
55
56
# File 'lib/test_temp_file_helper.rb', line 51

def mkfile(relative_path, content: '')
  mkdir File.dirname(relative_path)
  filename = File.join self.tmpdir, relative_path
  File.open(filename, 'w') {|f| f << content}
  filename
end

#teardownObject

Removes all files and directories created by the instance. Should be called from the test’s teardown method.



60
61
62
# File 'lib/test_temp_file_helper.rb', line 60

def teardown
  FileUtils.remove_entry @tmpdir
end