Ruby's standard library includes a class for creating temporary directories. Similar to Tempfile Show archive.org snapshot it creates a unique directory name.
Note:
Dir.mktmpdir(['foo', 'bar']) => /tmp/foo20220912-14561-3g93n1bar
Dir.tmpdir
e.g. Dir.mktmpdir('foo', Rails.root.join('tmp')) => /home/user/rails_example/tmp/foo20220912-14561-pyr8qd
. This might be necessary when your tests are running on CI. For this you might also want to commit tmp/.gitkeep
to git so the tmp
dir inside your project is present.Dir.mktmpdir('exports')
=> "/tmp/exports20220912-14561-pobh0a"
When creating directories in parallel tests manually, you normally need to handle these issues:
tmp/some-test-folder
you might end up in flaky specs.#mktmpdir
solves these. However, you should still remove them after you're done. Here are three options:
it 'does something with a temporary directory' do
Dir.mktmpdir('exports') do |export_folder_path|
# ...
end
end
it 'does something with a temporary directory' do
export_path = Dir.mktmpdir('exports')
# ...
ensure
FileUtils.remove_entry(export_path)
end
before { @export_path = Dir.mktmpdir('exports') }
after do
if @export_path.present?
FileUtils.remove_entry(@export_path)
end
end
it 'does something with a temporary directory' do
# ...
end
Use something like "#{Rails.env}#{ENV['TEST_ENV_NUMBER']}"
in you directory path when using Dir.mkdir
.
Further reading: