gpt4 book ai didi

ruby-on-rails - Factorybot - 如何设置嵌套属性

转载 作者:行者123 更新时间:2023-12-04 03:54:52 25 4
gpt4 key购买 nike

我相信最好创建一个新问题...它遵循 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

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

不知道size属性怎么写,我的produt还是无效(缺少size)

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

最佳答案

创建尺寸工厂

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

关于ruby-on-rails - Factorybot - 如何设置嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com