Factorybot-如何设置嵌套属性

时间:2019-02-11 14:49:37

标签: ruby-on-rails factory-bot

我相信最好还是提出一个新问题... my previous question我的模型产品有很多尺寸(嵌套属性)

我想创建工厂,但是我无法使其工作...

产品至少具有一个尺寸(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...

2 个答案:

答案 0 :(得分:1)

创建尺寸工厂

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

答案 1 :(得分:1)

您必须定义尺寸的工厂

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

和产品

FactoryBot.define do
  factory :product do
    association :size
    title { Faker::Artist.name}
    ...
  end
end

或在:product工厂中添加构建回调

after :build do |product|
  product.sizes << create(:size)
end