Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
Avoid using fixture_file_upload with FactoryGirl and Paperclip

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.

Comments
  1. Kostya says:

    It seems it donesn’t work with validates_attachment_presence validation.

  2. Pedro says:

    Worked great! Thanks!

  3. Ana says:

    Great explanation. Thanks for sharing! It was just what I needed for this project.

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *