Skip to content

Instantly share code, notes, and snippets.

@masasakano
Created August 26, 2022 13:35
Show Gist options
  • Save masasakano/16c9627743706cac2a5b8a3e617497c6 to your computer and use it in GitHub Desktop.
Save masasakano/16c9627743706cac2a5b8a3e617497c6 to your computer and use it in GitHub Desktop.
Ruby minitest/unit-test template for using Tempfile
gem "minitest"
require 'minitest/autorun'
require 'tempfile'
# In general, each test method should generate its own temporary files.
# With the following code, the temporary files will be automatically deleted
# at the end of the processing, even if their IOs have been alraedy closed
# and only the filename (path) were utilised during processing.
class TestUnitMyLibrary < MiniTest::Test
def setup
# Array of IOs for temporary files (automatically set in generate_tmpfile())
@tmpfiles = []
end
def teardown
@tmpfiles.each do |ef|
ef.close if !ef.closed?
File.unlink(ef.path)
end
end
# @option root [#to_s] Root-name of the temporary filename
def generate_tmpfile(root=File.basename($0))
io_tmpfile = Tempfile.open(root.to_s)
$stderr.print "TEST: Tmpfile="+io_tmpfile.path if ENV.key?('PRINT_TMPFILE') # To display Filename (NOTE the file will be removed when the script ends anyway.)
@tmpfiles.push io_tmpfile
[io_tmpfile, io_tmpfile.path]
end
def test_method1
io_tmp, path_tmp = generate_tmpfile(__method__)
io_tmp.puts "my message" # Write to a temporary file
io_tmp.rewind
msg_log = io_tmp.read # Read the contents of the temporary file
# You can use only the filename (path), if desired.
io_tmp.close
system "echo abc > #{path_tmp}"
# the file is automatically deleted at the end.
end
end
#
# If a single method uses a temporary file, the following is suffice.
#
require 'tempfile'
class TestUnitMyLibrary < MiniTest::Test
def setup
@io_tmpfile = Tempfile.open('test_pandoc')
@tmpfilename = @io_tmpfile.path
$stderr.print "TEST: Tmpfile="+@tmpfilename if ENV.key?('PRINT_TMPFILE') # To display Filename (NOTE the file will be removed when the script ends anyway.)
end
def teardown
if !@io_tmpfile.closed?
@io_tmpfile.close
end
File.unlink(@tmpfilename) if File.exist?(@tmpfilename)
end
def test_method1
@io_tmpfile.puts "my message"
@io_tmpfile.rewind
msg_log = @io_tmpfile.read
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment