gpt4 book ai didi

ruby-on-rails - 如何使用Factory Girl生成回形针附件?

转载 作者:行者123 更新时间:2023-12-03 04:36:28 25 4
gpt4 key购买 nike

我有一个包含许多图像的模型 Person,其中图像有一个称为数据的回形针附件字段,下面显示了缩写版本:

class Person
has_many :images
...
end

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

一个人必须至少附有一张图片。

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

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

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

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

...

有时测试会成功运行。

谁能告诉我我遇到的问题是什么,或者他们如何一起使用 FactoryGirl 和 Paperclip 来实现我想要实现的目标?

我正在使用 Rails 3。

最佳答案

您可以使用fixture_file_upload

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

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 需要存在于应用程序的根目录中。

请注意,FactoryBotFactoryGirl 的新名称。

关于ruby-on-rails - 如何使用Factory Girl生成回形针附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3294824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com