Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using factory_girl with PaperClip 4.0

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?

like image 332
steakchaser Avatar asked Feb 03 '14 22:02

steakchaser


1 Answers

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.

like image 115
Hayden Ball Avatar answered Oct 17 '22 23:10

Hayden Ball