attributes_forとは
プロジェクトファクトリからテスト用の属性値をハッシュとして作成するもの。
buildとの違い
user
とpost
のfactoryがあったとする。
users.rb
FactoryBot.define do
factory :user do
name "test"
sequence(:email) { |n| "test#{n}@test.com"}
password "password"
end
end
posts.rb
FactoryBot.define do
factory :post do
content 'test content'
association :user
end
end
これらを用いたbuild
とattributes_for
で取得するデータの違いが以下の通り。
> FactoryBot.build(:post)
=> <Post id: nil, content: "test content", user_id: 8, created_at: nil, updated_at: nil>
> FactoryBot.attributes_for(:post)
=> {:name=>"test", :email=>"test2@test.com", :password=>"password"}
build
はモデルオブジェクトとして返り、attributes_for
はハッシュとして返ることが分かった。