ruby-on-rails - Factorybot - 如何设置嵌套属性
问题描述
我相信最好创建一个新问题......它遵循我之前的问题我的模型产品有很多尺寸(嵌套属性)
我想创建工厂,但我不能让它工作......
如果产品至少具有一种尺寸 (size_name
和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
在控制器规范中
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...
解决方案
为尺寸创建工厂
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
推荐阅读
- optimization - tanh(mean + std*z) 的对数似然逼近器
- python-3.x - 读取存储在列表中的索引
- angularjs - 在 Angular Routing 中配置列表和网格视图
- deployment - 戴尔 Boomi 的 CI/CD
- java - 执行器池未处理所有项目
- sql - 如何检查未分配给任何用户但 oracle 默认用户(root、系统等)的所有角色?
- glsl - WebGL 在三角形内插入参考颜色
- java - Javafx-FXMLLoader 的加载方法无法创建 Controller 类的实例
- batch-file - 如何从支持不同用户的用户文件夹中制作批处理脚本复制文件?
- c++ - 使用 pin 添加您自己的说明