method

fixture_file_upload

Importance_2
v3.0.9 - Show latest stable - 2 notes - Class: ActionDispatch::TestProcess
fixture_file_upload(path, mime_type = nil, binary = false) public

Shortcut for ARack::Test::UploadedFile.new(ActionController::TestCase.fixture_path + path, type):

post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')

To upload binary files on Windows, pass :binary as the last parameter. This will not affect other platforms:

post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
Show source
Register or log in to add new notes.
July 23, 2010
2 thanks

To use in testing

If you want to use this in a test, add the following to test_helper.rb:

include ActionDispatch::TestProcess

(If using factory_girl, you can call it in your Factory, like so:

f.photo { fixture_file_upload 'test.png', 'image/png' }
January 31, 2012
2 thanks

To use with factory_girl and prevent leaking file handles

As insane-dreamer noted, to use with factory_girl:

Factory :video_file do
  file { fixture_file_upload 'test.png', 'image/png' }
end

However, I ran into an issue where one of our spec’s was creating a few hundred files and would then crash with:

Errno::EMFILE: Too many open files

If you look at the source code for fixture_file_upload, it creates a new file. I don’t know if these files were being leaked, or just not getting garbage collected, but they never got closed. Eventually they just piled up and the process hit the max open file limit.

So, you need to explicitly call close on the file handle returned from fixture_file_upload. However, you can’t call close in the block immediately after fixture_file_upload because the factory needs to be able to read from the stream in order to properly initialize ‘file’.

Instead what I had to do was perform the close on the ‘proxy’ in an after_create block, like so

Factory :video_file do
  file { fixture_file_upload 'test.png', 'image/png' }

  after_create do |video, proxy|
    proxy.file.close
  end
end