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
Is Data Scientist the Sexiest Job of the Century?
Is Data Scientist the Sexiest Job of the Century?

Hey good lookin'. Yep, I'm talking to you, or at least the data scientists reading this. (The rest of you a...

Next
Ah, ah, ah. Now, that was silly. Wouldn't you agree, my bats? Ah, ah, ah.
Ah, ah, ah. Now, that was silly. Wouldn't you agree, my bats? Ah, ah, ah.

Helps Slow count after delete_all of millions of records? font icons, Ajax, and IE8 Our application is usi...

Enter curious. Exit smarter.

Register Now