FactoryGirl / Bot 图像定义

FactoryGirl / Bot image definitions

我有一个功能测试。在此功能测试中,我需要将一些数据加载到测试数据库中: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

但是,我得到一个错误,因为我的视图需要生成图像 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