官方文件有說有以下建立方式至於差別在哪呢?
# Returns a User instance that's not saved
user = build(:user)
# Returns a saved User instance
user = create(:user)
# Returns a hash of attributes that can be used to build a User instance
attrs = attributes_for(:user) # {name: 'CK', phone: '123'}
# Returns an object with all defined attributes stubbed out
stub = build_stubbed(:user)
# Passing a block to any of the methods above will yield the return object
create(:user) do |user|
user.posts.create(attributes_for(:post))
end
create
=> 真的寫進db
build
=> 還沒save 且 id為 nil
build_stubbed
=> stub 的概念創建一個假的實體而且還有 id
attributes_for
=> 拿到 FactoryBot 的 attribute
我平常使用起來,如果你建立的資料能不進就不進!速度會快上很多!
因為有時候建立資料的時候關聯的問題可能你只需要測試 profile
但一定要有 user
,這時候 user
就可以用 build_stubbed
,既能拿到資料也能不會進db commit!
如果還是不懂build、create、build_stubbed的可以看看這篇
FactoryGirl create vs build vs build_stubbed
attributes_for