ruby-on-rails – 将FactoryGirl的attributes_for与Paperclip附件一起使用

我有一个名为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>

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

解决方法

作为解决方法,您可以将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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...