[英]What is the point of nested factories?
I just don't know what they're for. 我只是不知道他们是干什么的。 Before I thought they were for populating foreign keys easily but now I see that's not the case. 在我以为它们是用于轻松填充外键之前,但现在我发现情况并非如此。
# User attributes: id, name, password
factory :user_0, class: User do
id 0
name "Jimmy"
password "Jimson"
end
# Status attributes: id, user_id, content
factory :user_0_statuses, class: Status do
association :user, factory: :user_0
factory :user_0_status_0 do
id 0
content "noo"
end
factory :user_0_status_1 do
id 1
content "yees"
end
end
When :user_0_status_0 and :user_0_status_1 factories are .create
d in a spec, I thought that this factory setup would create the following in the database (note the status' user_id entries.): 当:user_0_status_0和:user_0_status_1工厂在规范中是.create
d时,我认为此工厂设置将在数据库中创建以下内容(请注意状态的user_id条目。):
users
id | name | password
0 | Jimmy | Jimson
statuses
id | user_id | content
0 | 0 | noo
1 | 0 | yees
But instead it creates this: 但是,它创建了以下代码:
users
id | name | password
0 | Jimmy | Jimson
0 | Jimmy | Jimson
statuses
id | user_id | content
0 | nil | noo
1 | nil | yees
Basically, a brand new user based on the user_0 factory is created for every nested status factory, and the user_id of the status isn't set at all. 基本上,将为每个嵌套状态工厂创建一个基于user_0工厂的全新用户,并且根本不会设置状态的user_id。 How is this behaviour useful? 这种行为有何用处?
I just can't see any use at all regarding nested factories. 对于嵌套工厂,我什至看不到任何用处。 What are they, and the association method, for? 它们和关联方法是做什么用的?
When a factory is nested inside another factory definition, it inherits the attributes defined in the parent factory. 当工厂嵌套在另一个工厂定义中时,它将继承父工厂中定义的属性。 If you had a User factory, you could nest an "admin_user" factory inside of it that would have all the base user characteristics plus whatever makes an user an admin without having to redefine the base attributes twice. 如果您有一个用户工厂,则可以在其中嵌套一个“ admin_user”工厂,该工厂将具有所有基本用户特征以及使用户成为管理员的所有条件,而不必重新定义基本属性。
(slightly unrelated: I'm not sure if setting the primary key (is Status is an ActiveRecord class) is a reliable practice, and I'd advise finding another way to solve that problem.) (略微无关:我不确定是否设置主键(Status是ActiveRecord类)是否是可靠的做法,我建议您找到其他方法来解决该问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.