構建策略的factory_bot 檔案說:
factory_bot 支持幾種不同的構建策略:build、create、attributes_for 和 build_stubbed
并繼續使用一些示例。但是,它并沒有明確說明每個結果是什么。我已經使用create了build一段時間了。attributes_for從描述中看起來很簡單,我看到了它的一些用途。然而,什么是build_stubbed?描述說
回傳一個物件,其中所有已定義的屬性都被剔除
“被淘汰”是什么意思?這與createor有什么不同build?
uj5u.com熱心網友回復:
讓我們考慮一下這些工廠示例的區別:
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.all # => [<Post:0x00007fd10f824168> {...}]
# User also created in the database
User.all # => [<User:0x00007f91af405b30> {...}]
build_stubbed
build_stubbed模仿創造。它包含、id和created_at屬性。它還跳過所有驗證和回呼。updated_atuser_id
存根意味著FactoryBot只需初始化物件并將值分配給id created_at和updated_at屬性,使其看起來就像 created。因為id它分配整數1001(1001 只是 FactoryBot 用來分配給 id 的默認數字),created_at并updated_at分配當前日期時間。對于使用 is 創建的每條其他記錄,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://www.uj5u.com/net/493383.html
