如何使用Factory Girl生成回形针附件? [英] How Do I Use Factory Girl To Generate A Paperclip Attachment?

查看:68
本文介绍了如何使用Factory Girl生成回形针附件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的人物模型有很多图像,其中图像有一个名为data的回形针附件字段,缩写形式显示在下面:

I have model Person that has many Images, where images has a Paperclip attachment field called data, an abbreviated version displayed below:

class Person
  has_many :images
  ...
end

class Image
  has_attached_file :data
  belongs_to :person
  ...
end

要求人员至少附有一张图片.

Person is required to have at least one Image attached to it.

使用FactoryGirl时,我的代码类似于以下内容:

When using FactoryGirl, I have code akin to the following:

Factory.define :image do |a|
  a.data { File.new(File.join(Rails.root, 'features', 'support', 'file.png')) }
  a.association :person
end

Factory.define :person do |p|
  p.first_name 'Keyzer'
  p.last_name 'Soze'
  p.after_create do |person|
    person.assets = [Factory.build(:image, :person => person)]
  end
  # p.images {|images| [images.association(:image)]}
end

(注:我也尝试过上面注释掉的代码,也尝试过) 在大多数时候,我运行黄瓜功能时,会收到类似于以下内容的错误:

(N.B. I have also tried the code commented out above was also tried) Most of the time when I run cucumber features, I get an error akin to the following:

没有这样的文件或目录-/tmp/stream,9887,0.png(Errno :: ENOENT)

No such file or directory - /tmp/stream,9887,0.png (Errno::ENOENT)

...

有时测试运行成功.

有人可以告诉我我在这里遇到什么问题吗,或者他们如何一起使用FactoryGirl和Paperclip来实现我想要实现的目标?

Can anyone tell me what the problem is I am having here or how they use FactoryGirl and Paperclip together to achieve something like what I am trying to achieve?

我正在使用Rails 3.

I am using Rails 3.

推荐答案

您可以使用 fixture_file_upload

include ActionDispatch::TestProcess在您的测试助手中,这是一个示例工厂:

include ActionDispatch::TestProcess in your test helper, here is an example factory:

include ActionDispatch::TestProcess

FactoryBot.define do
  factory :user do
    avatar { fixture_file_upload(Rails.root.join('spec', 'photos', 'test.png'), 'image/png') }
  end
end

在上面的示例中,运行测试之前,spec/photos/test.png必须存在于应用程序的根目录中.

In the above example, spec/photos/test.png needs to exist in your application's root directory before running your tests.

请注意,FactoryBotFactoryGirl的新名称.

这篇关于如何使用Factory Girl生成回形针附件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆