Class: TestTempFileHelper::TempFileHelper
- Inherits:
-
Object
- Object
- TestTempFileHelper::TempFileHelper
- Defined in:
- lib/test_temp_file_helper.rb
Overview
Automatically generates and cleans up temporary files in automated tests. Performs its operations in the directory specified by the TEST_TMPDIR environment variable.
Instance Method Summary collapse
-
#initialize(tmpdir: nil) ⇒ TempFileHelper
constructor
A new instance of TempFileHelper.
-
#mkdir(relative_path) ⇒ String
Creates a temporary test directory relative to TEST_TMPDIR.
-
#mkfile(relative_path, content: '') ⇒ String
Creates a temporary file relative to TEST_TMPDIR.
-
#teardown ⇒ Object
Removes all files and directories created by the instance.
Constructor Details
#initialize(tmpdir: nil) ⇒ TempFileHelper
25 26 27 28 29 |
# File 'lib/test_temp_file_helper.rb', line 25 def initialize(tmpdir: nil) @tmpdir = tmpdir || ENV['TEST_TMPDIR'] @files = [] @dirs = [] end |
Instance Method Details
#mkdir(relative_path) ⇒ String
Creates a temporary test directory relative to TEST_TMPDIR.
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/test_temp_file_helper.rb', line 34 def mkdir(relative_path) components = relative_path.split(File::SEPARATOR) components = components.delete_if {|i| i == '.'} current = @tmpdir until components.empty? current = File.join current, components.shift Dir.mkdir current unless File.exists? current @dirs << current end @dirs.last end |
#mkfile(relative_path, content: '') ⇒ String
Creates a temporary file relative to TEST_TMPDIR.
50 51 52 53 54 55 56 |
# File 'lib/test_temp_file_helper.rb', line 50 def mkfile(relative_path, content: '') mkdir File.dirname(relative_path) filename = File.join(@tmpdir, relative_path) File.open(filename, 'w') {|f| f << content} @files << filename filename end |
#teardown ⇒ Object
Removes all files and directories created by the instance. Should be called from the test’s teardown method.
60 61 62 63 |
# File 'lib/test_temp_file_helper.rb', line 60 def teardown @files.sort.uniq.each {|f| File.unlink f} @dirs.sort.uniq.reverse.each {|d| Dir.rmdir d} end |