Search code examples
ruby-on-railsrubyrubygemstestunit

How to generate a temporary file for use in a unit test?


The method to test allows adding a path to additional files the user adds which contain data.

For example, the user might store a file called data.txt in the /workspace/data directory. And we want to add the path to this directory to an already existing array called DATA_PATH.

Method:

def add_custom_path(path)
  DATA_PATH.unshift(path)
end

Where path is a location in a Rails app where the user stores a file.

The gem uses test-unit.

Question:

Is there a way to temparily generate a file in some directory, run an assert_not_empty test, and then have the file disappear?

I don't have experience writing tests for gems so any guidance would be very appreciated.


Solution

  • The .create and .new methods of Ruby's Tempfile take a second argument which is the directory you want the file to be in, and files created by Tempfile are automatically deleted when the temporary file's File object is garbage-collected or Ruby exits. So you can create a temporary file,

    tempfile = Tempfile.new('filename', 'directoryname')
    

    write to it, do your test and let Ruby clean it up for you.

    Note that the first argument is not the entire unqualified name of the file, but a part to which Tempfile adds disambiguating characters, so you can safely do it more than once in a test suite.

    Also, if you need the file to have a particular suffix, you can do e.g.

    tempfile = Tempfile.new(['filename', '.rb'], 'directoryname')