Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FactoryGirl's attributes_for with Paperclip attachment

I have a model called Photo that has a Paperclip attachment called image.

I have working specs testing the creation of a new Photo with attachment and can create them manually.

I have the following FactoryGirl factory used throughout my specs:

FactoryGirl.define do
 factory :photo do
    image { File.new(File.join(Rails.root, 'spec', 'fixtures', 'images', 'minimum.jpg')) }
    # Other attributes omitted
 end
end

I need to use attributes_for(:photo) to generate attributes to pass into PhotoController's create action, but doing so causes Paperclip to raise an error:

Paperclip::AdapterRegistry::NoHandlerError:
       No handler found for "#<File:0x007f87c0a1d980>"

I can see that if I create a new Photo using the browser, the image attribute looks like this:

"image"=>#<ActionDispatch::Http::UploadedFile:0x007fbc480b1c18 @tempfile=#<Tempfile:/var/folders/bv/x495g9g10m7119680c9ssqmr0000gn/T/RackMultipart20140622-45603-a1h9a8>, @original_filename="equals_cover_art_old.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"equals_cover_art_old.jpg\"\r\nContent-Type: image/jpeg\r\n">}

However the image attribute generated by attributes_for(:photo) looks like this:

:image=>#<File:/Users/me/Documents/Work/Websites/example/spec/fixtures/images/minimum.jpg>

How can I generate the correct object from a call to attributes_for(:photo) or work around it?

like image 965
Undistraction Avatar asked Jan 11 '23 08:01

Undistraction


2 Answers

As a workaround, you can set the image attribute to a Rack::Test::UploadedFile instance instead of File.

FactoryGirl.define do
  factory :photo do
    image Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/images/minimum.jpg", "image/jpg")
    # Other attributes
  end
end
like image 109
Kirti Thorat Avatar answered Jan 12 '23 22:01

Kirti Thorat


An alternative workaround using ActionDispatch::TestProcess:

include ActionDispatch::TestProcess

FactoryGirl.define do
  factory :photo do
    image { fixture_file_upload( File.join(Rails.root, 'spec', 'fixtures', 'images', 'minimum.jpg'), 'image/jpeg') }
  end
end
like image 31
Undistraction Avatar answered Jan 12 '23 20:01

Undistraction