我有一个名为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"=>#<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>
解决方法
作为解决方法,您可以将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