我有一个模型Person,它有许多图像,其中图像有一个名为data的回形针附件字段,下面显示的是一个缩写版本:
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特性时,我得到一个类似于以下内容的错误:
没有这样的文件或目录- /tmp/stream,9887,0.png (错误号::ENOENT)
..。
有时测试会成功运行。
谁能告诉我我在这里遇到了什么问题,或者他们是如何一起使用FactoryGirl和回形针来实现我正在努力实现的目标?
我使用的是Rails3。
发布于 2012-04-03 05:06:22
您可以使用fixture_file_upload
include 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
需要存在于应用程序的根目录中。
请注意,FactoryBot
是FactoryGirl
的新名称。
发布于 2013-06-28 10:52:13
较新的FG语法,不包含必需的语法
factory :user do
avatar { File.new(Rails.root.join('app', 'assets', 'images', 'rails.png')) }
end
或者更好的是,
factory :user do
avatar { File.new("#{Rails.root}/spec/support/fixtures/image.jpg") }
end
发布于 2013-11-22 05:48:05
Desmond Bowe在Pivotal实验室的suggests avoiding fixture_file_upload由于内存泄漏问题。相反,您应该直接在工厂中设置回形针字段:
factory :attachment do
supporting_documentation_file_name { 'test.pdf' }
supporting_documentation_content_type { 'application/pdf' }
supporting_documentation_file_size { 1024 }
# ...
end
https://stackoverflow.com/questions/3294824
复制相似问题