Using factory_girl with PaperClip 4.0
Asked Answered
B

1

8

Does anyone know the proper way to create PaperClip 4.0 attachments with factory_girl, bypassing any of the PaperClip processing and validation?

I used to just be able to do the following in my factory:

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

This would basically trick PaperClip into thinking that there was a valid attachment.

After upgrading from 3.5.3 to 4.0, I now get a validation error:

ActiveRecord::RecordInvalid: Validation failed: Image translation missing: en.activerecord.errors.models.attachment.attributes.supporting_documentation.spoofed_media_type

NOTE: The original discussion for PaperClip 3.X is here: How Do I Use Factory Girl To Generate A Paperclip Attachment?

Bullpen answered 3/2, 2014 at 22:29 Comment(1)
Opened issue in Paperclip repo: github.com/thoughtbot/paperclip/issues/1432Bullpen
G
4

The issue appears to be caused by line 61 in media_type_spoof_detector.

Paperclip is trying to find the mime type of the "file" you have uploaded. When there isn't one, it's failing validation to protect you from file type spoofing.

I haven't tried this myself, but perhaps your best bet would be to use a real file, and set it using the fixture_file_upload method from ActionDispatch::TestProcess.

factory :attachment do
   supporting_documentation { fixture_file_upload 'test.pdf', 'application/pdf' }

   # This is to prevent Errno::EMFILE: Too many open files
   after_create do |attachment, proxy|
     proxy.supporting_documentation.close
   end
end

You will need to include ActionDispatch::TestProcess in test_helper.rb

This was first posted here.

Gadoid answered 1/5, 2014 at 22:32 Comment(4)
Hm, does pivotallabs.com/… still apply?Marnimarnia
I believe this is the reason for the after_create hook, that correctly closes the temp file? I might be wrong though...Gadoid
Can you explain how the after_create hook works? I'm having trouble getting that to work. What is proxy supposed to be? When I run my test, proxy is nil.Eclogite
after_create should run once FactoryGirl has created the model. The second parameter should be the object that FactoryGirl used to create the model. See the "has_many" section of rubydoc.info/gems/factory_girl/file/… for more details.Gadoid

© 2022 - 2024 — McMap. All rights reserved.