我有一个功能测试。在此功能测试中,我需要将一些数据加载到测试数据库中: let!(:product1) { create(:product) }
我正在使用 FactoryBot 创建 :product 对象并将其保存到数据库:
FactoryBot.define do
factory :product do
name 'Master Coat'
color 'black'
size 'M'
price '870'
available true
order 1
image_1 '/assets/images/test_image.jpeg'
image_2 '/assets/images/test_image.jpeg'
image_3 '/assets/images/test_image.jpeg'
image_4 '/assets/images/test_image.jpeg'
image_5 '/assets/images/test_image.jpeg'
image_6 '/assets/images/test_image.jpeg'
end
end
我运行我的 RSpec 测试:
describe 'GET #detail' do
it 'should return only products with a specified name' do
visit detail_path(name: 'Master Coat')
end
end
但是,我收到错误,因为我的 View 需要生成图像 1、2 等,而在我的实际应用程序中,这些图像是通过 url 从 AWS 加载的。但在我的测试中,我不想向 AWS 发送请求,因为我没有测试图像。加载的图像无关紧要。我只想在我的 app/assets/images/test_image.jpeg
目录中有一个虚拟图像,并让 FactroyBot 使用该图像进行所有测试,但我无法让它工作,因为我不正确指定图像和 FactoryBot 的路径给我一个错误:
ActionView::Template::Error:
The asset "assets/images/test_image.jpeg" is not present in the asset pipeline.
我尝试了几种不同的方法来让它发挥作用。指定图像文件夹的 url 以便 FactoryBot 可以检索虚拟图像的正确方法是什么?这是最好的方法还是他们的更好方法?
最佳答案
只需删除路径即可。当您使用 image_tag('test_image.jpeg')
时,rails 将在 app/assets/images
中查找。您还可以将文件放在公共(public)目录中,它们将被静态提供,而不是通过管道。
FactoryBot.define do
factory :product do
name 'Master Coat'
color 'black'
size 'M'
price '870'
available true
order 1
(1..6).each {|n| send "image_#{n}", 'test_image.jpeg' }
end
end
关于ruby-on-rails - FactoryGirl/Bot 图像定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47840166/