Factory-bot - How to build association and nested attributes

China☆狼群 提交于 2019-12-24 07:06:32

问题


I am new to Factories and I need help for the association and nested attributes....

  • How do I set an admin user that creates a product? OK
  • How do I set category to a product? Ok
  • How do I attach images to a product? OK

  • How do I set product's sizes (nested attibutes)

user.rb

 has_many :products

product.rb

belongs_to :user
belongs_to :category
has_many :sizes, inverse_of: :product, dependent: :destroy #nested_attributes 

size.rb

belongs_to :product

category.rb

has_many :products

factories/users.rb

  FactoryBot.define do
    factory :user do 
        first_name        { Faker::Name.first_name}
        last_name         { Faker::Name.last_name }
        admin             { [false, true].sample }
        sequence(:email)  { |n| "#{n}#{Faker::Internet.email}" }
        birth_date        {"20/10/1997"}
        password          { 'password'}
    end 
  end

factories/categories.rb

FactoryBot.define do
  factory :category do
    title { Faker::Artist.name }
  end
end

factories/sizes.rb

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

factories/products.rb

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) }
    size
    category
    # how to set an admin ?? 
  end
end

回答1:


Add associations like this

For product

FactoryBot.define do 
    factory :product do
      user {User.first || association(:user)}
      user {User.first || association(:user, admin: true)}
      # your admin attribute (role: admin or admin: true) whatever you are using for admin
      category {Category.first || association(:category)}
    end
end

Read FactoryBot association hope it will help.



来源:https://stackoverflow.com/questions/54627798/factory-bot-how-to-build-association-and-nested-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!