1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

attributes_forとは【rspec】

Posted at

attributes_forとは

プロジェクトファクトリからテスト用の属性値をハッシュとして作成するもの。

buildとの違い

userpostの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

これらを用いたbuildattributes_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はハッシュとして返ることが分かった。

参考記事

【Rspec】attributes_forってなんだ...

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?