将FactoryGirl的attributes_for与Paperclip附件一起使用

时间:2014-06-22 20:34:52

标签: ruby-on-rails ruby ruby-on-rails-4 paperclip factory-bot

我有一个名为Photo的模型,其中包含一个名为image的Paperclip附件。

我有工作规格测试创建带附件的新照片,并可以手动创建。

我的规格中使用了以下FactoryGirl工厂:

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

我需要使用attributes_for(:photo)生成属性以传递给PhotoController的创建操作,但这样做会导致Paperclip引发错误:

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

我可以看到,如果我使用浏览器创建新的照片,image属性如下所示:

"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">}

然而attributes_for(:photo)生成的图像属性如下所示:

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

如何通过致电attributes_for(:photo)生成正确的对象或解决它?

2 个答案:

答案 0 :(得分:7)

作为一种变通方法,您可以将image属性设置为Rack::Test::UploadedFile个实例,而不是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

答案 1 :(得分:2)

使用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