首页 > 解决方案 > Factorybot - 如何设置嵌套属性

问题描述

我相信最好创建一个新问题......它遵循我之前的问题我的模型产品有很多尺寸(嵌套属性)

我想创建工厂,但我不能让它工作......

如果产品至少具有一种尺寸 (size_namequantity) ,则该产品是有效的

FactoryBot.define do
  factory :product do
    title { Faker::Artist.name}
    ref   { Faker::Number.number(10)}
    price { Faker::Number.number(2) }
    color { Faker::Color.color_name }
    brand { Faker::TvShows::BreakingBad }
    description { Faker::Lorem.sentence(3) }
    attachments { [
      File.open(File.join(Rails.root,"app/assets/images/seeds/image.jpg")),

    ] }
    user { User.first || association(:user, admin: true)}
    category { Category.first }


    # SOLUTION 1
    factory :size do 
       transient do 
         size_name {["S", "M", "L", "XL"].sample}
          quantity  { Faker::Number.number(2) }
        end
     end
   # SOLUTION 2 
    after(:create) do |product|
       create(:size, product: product)
     end

  # SOLUTION 3 
    initialize_with { attributes }
   # Failure/Error: @product = create(:product, category_id: category.id)
   # NoMethodError:
   # undefined method `save!' for #<Hash:0x007ff12f0d9378>
  end
end

在控制器规范中

  before(:each) do 
    sign_in FactoryBot.create(:user, admin: true)
    category = create(:category)
    @product = create(:product, category_id: category.id)
  end

我不知道如何写 size 属性,我的产品仍然无效(缺少尺寸)

我得到的错误是validation failed,Product must exist...

标签: ruby-on-railsfactory-bot

解决方案


为尺寸创建工厂

FactoryBot.define do
  factory :size do
    size_name {["S", "M", "L", "XL"].sample}
    quantity  { Faker::Number.number(2) }
    product
  end
end

一个用于产品

 FactoryBot.define do
   factory :product do
    title { Faker::Artist.name}
    ref   { Faker::Number.number(10)}
    price { Faker::Number.number(2) }
    color { Faker::Color.color_name }
    brand { Faker::TvShows::BreakingBad }
    description { Faker::Lorem.sentence(3) }
    attachments { [
      File.open(File.join(Rails.root,"app/assets/images/seeds/image.jpg")),
    ] }
    user { User.first || association(:user, admin: true)}
    category 
  end
end

推荐阅读