ruby on rails - How to generate a temporary file for use in a unit test? -
the method test allows adding path
additional files user adds contain data.
for example, user might store file called data.txt
in /workspace/data
directory. , want add path directory existing array called data_path
.
method:
def add_custom_path(path) data_path.unshift(path) end
where path
location in rails app user stores file.
the gem uses test-unit
.
question:
is there way temparily generate file in directory, run assert_not_empty
test, , have file disappear?
i don't have experience writing tests gems guidance appreciated.
the .create
, .new
methods of ruby's tempfile
take second argument directory want file in, , files created tempfile
automatically deleted when temporary file's file
object garbage-collected or ruby exits. can create temporary file,
tempfile = tempfile.new('filename', 'directoryname')
write it, test , let ruby clean you.
note first argument not entire unqualified name of file, part tempfile
adds disambiguating characters, can safely more once in test suite.
also, if need file have particular suffix, can e.g.
tempfile = tempfile.new(['filename', '.rb'], 'directoryname')