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?

Community
  • 1
  • 1
steakchaser
  • 5,198
  • 1
  • 26
  • 34

1 Answers1

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.

Hayden Ball
  • 307
  • 5
  • 13
  • 1
    Hm, does http://pivotallabs.com/avoid-using-fixture-file-upload-with-factorygirl-and-paperclip/ still apply? – phillbaker May 10 '14 at 19:27
  • I believe this is the reason for the `after_create` hook, that correctly closes the temp file? I might be wrong though... – Hayden Ball May 10 '14 at 23:05
  • 1
    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. – Daniel Bonnell May 29 '15 at 18:01
  • `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 http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Associations for more details. – Hayden Ball May 31 '15 at 09:20