factory_bot支持几种不同的构建策略:构建、创建、attributes_for和build_stubbed
并继续给出一些用法的例子。然而,它并没有清楚地说明每一个结果是什么。我使用create
和build
已经有一段时间了。从描述中看,attributes_for
似乎很简单,我看到了它的一些用途。然而,什么是build_stubbed
?描述说
返回一个具有所有已定义属性的对象。
“擦出”是什么意思?这与create
或build
有何不同?
发布于 2022-06-18 05:57:27
让我们考虑一下这些工厂的例子的不同之处:
FactoryBot.define do
factory :post do
user
title { 'Post title' }
body { 'Post body' }
end
end
FactoryBot.define do
factory :user do
first_name { 'John' }
last_name { 'Doe' }
end
end
构建
使用build
方法,一切都很简单。它返回一个未保存的Post
实例
# initialization
post = FactoryBot.build(:post)
# call
p post
p post.user
# output
#<Post:0x00007fd10f824168> {
:id => nil,
:user_id => nil,
:title => "Post title",
:body => "Post body",
:created_at => nil,
:updated_at => nil
}
#<User:0x00007f8792ed9290> {
:id => nil,
:first_name => "Post title",
:last_name => "Post body",
:created_at => nil,
:updated_at => nil
}
Post.all # => []
User.all # => []
创建
使用create
,一切都是显而易见的。它保存并返回一个Post
实例。但是它调用所有的验证和回调,并创建User
的相关实例。
# initialization
post = FactoryBot.create(:post)
# call
p post
p post.user
# output
#<Post:0x00007fd10f824168> {
:id => 1,
:user_id => 1,
:title => "Post title",
:body => "Post body",
:created_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00,
:updated_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00
}
#<User:0x00007f8792ed9290> {
:id => 1,
:first_name => "John",
:last_name => "Joe",
:created_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00,
:updated_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00
}
在数据库中创建了Post记录和相关用户记录:
Post.all # => [<Post:0x00007fd10f824168> {...}]
# User also created in the database
User.all # => [<User:0x00007f91af405b30> {...}]
build_stubbed
build_stubbed
模仿创建。它使用id
、created_at
、updated_at
和user_id
属性。此外,它跳过所有验证和回调。
存根意味着FactoryBot
只是初始化对象并将值赋值给id
、created_at
和updated_at
属性,这样看起来就像创建了的。对于id
,它分配整数号1001
(1001只是FactoryBot用来分配给id的缺省数字),created_at
和updated_at
分配当前的日期时间。对于使用build_stubbed
创建的其他每条记录,都会增加编号,将其分配给id 1。首先,FactoryBot
初始化user
记录并将1001
赋值给id
属性,而不是将其保存到数据库中,而是初始化post
记录并将1002
保存到id
属性,并将1001
添加到user_id
属性以进行关联,但也不将记录保存到数据库中。见下面的例子。
#initialization
post = FactoryBot.build_stubbed(:post)
# call
p post
p post.user
# output
# It looks like persisted instance
#<Post:0x00007fd10f824168> {
:id => 1002,
:user_id => 1001,
:title => "Post title",
:body => "Post body",
:created_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00,
:updated_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00
}
#<User:0x00007f8792ed9290> {
:id => 1001,
:first_name => "John",
:last_name => "Joe",
:created_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00,
:updated_at => Sat, 18 Jun 2022 05:32:17.122906000 UTC +00:00
}
没有在数据库中创建帖子和用户记录!
# it is not persisted in the database
Post.all # => []
# Association was also just stubbed(initialized) and there are no users in the database.
User.all # => []
https://stackoverflow.com/questions/72662800
复制相似问题