Paperclip::Attachment passed as string when using

2019-08-05 21:30发布

问题:

I am trying to create a functional test for paperclip 3.1.2 on rails 3.2.6 using FactoryGirl 3.0 and when i pass the file attachment my controller receives a string which is the file location and not the Paperclip::Attachment object.

My factory is:

include ActionDispatch::TestProcess
FactoryGirl.define do
   factory :artist do
    id 1
    name 'MyString'
    photo {fixture_file_upload("#{Rails.root}/test/fixtures/files/rails.png",'image/png')}
  end
end

And my test is:

test "should create artist" do
  assert_difference('Artist.count') do
    post :create, :artist => { name: @artist.name, photo: @artist.photo }, :html => { :multipart => true }
  end

  assert_redirected_to artist_path(assigns(:artist))
end

In my controller this :

params[:artist][:photo].class.name 

equals "String", but this passes when i add it to the test

assert @artist.photo.class.name == "Paperclip::Attachment"

My current workaround is to create the fixture_file_upload in the test :

test "should create artist" do
  assert_difference('Artist.count') do
    photo = fixture_file_upload("/files/rails.png",'image/png')
    post :create, :artist => { name: @artist.name, photo: photo }, :html => { :multipart => true }
  end

  assert_redirected_to artist_path(assigns(:artist))
end

which works but creates a "Rack::Test::UploadedFile" and so I'm pretty confused why my factory returns a "Paperclip::Attachment" when the same method is called to create them both.

Thanks in advance for any light that you can shed on this as obviously I would like to use the factory rather than defining the fixture_file_upload outside of it.

回答1:

Have you tried to replace

photo {fixture_file_upload("#{Rails.root}/test/fixtures/files/rails.png",'image/png')}

with

photo File.new("#{Rails.root}/test/fixtures/files/rails.png")

inside your factory.