Linked Questions

Popular Questions

Factorybot - How to set Nested attributes

Asked by At

I beleive it's better to create a new question... It follows my previous question my model product has many sizes (nested attributes)

I want to create Factories but I can't make it work...

A product is valid if it has at least one size (size_nameand quantity)

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

In the controller spec

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

I don't know how to write the size attribute, my produt is still not valid (missing the size)

The error I get is validation failed,Product must exist...

Related Questions