Avoid using fixture_file_upload with FactoryGirl and Paperclip

September 21, 2012 Desmond Bowe

Joe Moore and I are using FactoryGirl and Paperclip for file attachments. The factory for building our Attachment model looked like this:

 factory :attachment do
   supporting_documentation { fixture_file_upload('test.pdf', 'application/pdf') }
   # ...
 end

Yesterday our test suite began raising the following error:

 Failure/Error: let(:attachment) { FactoryGirl.create(:attachment) }
 Errno::EMFILE:
   Too many open files - /var/folders/3q/_15370v96jlbnxsk3whsks5c0000gn/T/test20120920-4004-7c2o9y.pdf

It turns out that Rails’ fixture_file_upload method does not close the temporary file it creates. We found a suggestion to prevent leaking file handles by adding an after_create block that manually closes the file. We tested this fix by looping through the model spec 1000 times. More tests passed, but it eventually blew up with the same error.

Using fixture_file_upload needlessly exercises Paperclip’s file uploading functionality instead of just creating the models we care about for our application. Instead, explicitly set the attributes Paperclip needs:

 factory :attachment do
   supporting_documentation_file_name { 'test.pdf' }
   supporting_documentation_content_type { 'application/pdf' }
   supporting_documentation_file_size { 1024 }
   # ...
 end

…and all of our tests passed.

Conclusion: in model factories, set the Paperclip attributes directly and don’t use fixture_file_upload.

About the Author

Biography

More Content by Desmond Bowe
Previous
Case Commons is looking for a DevOps Engineer
Case Commons is looking for a DevOps Engineer

At Pivotal Labs, one of the services we provide our clients is helping them interview and hire. Pivotal Lab...

Next
Fixing broken keyboard shortcuts in Adobe Illustrator
Fixing broken keyboard shortcuts in Adobe Illustrator

Keyboard commands are essential to using Adobe applications like Illustrator or Photoshop. Unfortunately, s...

Enter curious. Exit smarter.

Learn More