构建策略的factory_bot文档说:
factory_bot支持几种不同的构建策略:build、create、attributes_for和build_stub
并继续使用一些例子。然而,它并没有清楚地说明每一个的结果是什么。我用create
和build
已经有一段时间了。从描述来看,attributes_for
似乎很简单,我看到了它的一些用途。那么,build_stubbed
是什么呢?描述说
返回一个具有所有已定义属性的对象
什么是"存根"?的意思吗?这与create
或build
有何不同?
让我们考虑一下这些工厂的例子中的区别:
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的number增加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
}
Post和user记录没有在数据库中创建!!
# 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 # => []