LoginSignup
17
15

More than 5 years have passed since last update.

FactoryGirlのattributes_forがassociationを生成してくれない

Posted at

前提

# model
class Group
  has_many :users
end

class User
  belongs_to :group

  validates :group_id, presence: true
end

# factory
FactoryGirl.define do
  factory :user do
    sequence(:name) {|n| "user #{n}" } 
    group
  end
end

問題

user_params = FactoryGirl.attributes_for(:user)

上記では、usergroup_idが空になってハマりました。

原因

FactoryGirl attributes_for を読むと、明らかにassociationを生成してない

対応

user_params = FactoryGirl.build(:user).attributes

注意

attributesModelのカラム(プロパティ)なら行けますが、メソッドは対象外です。

よって、has_secure_password機能を使っている場合は、上記だけでは、passwordpassword_confirmationは空になってしまいます。

最終版

user = FactoryGirl.build(:user)
user_params = user.attributes.merge(password: user.password, password_confirmation: user.password_confirmation)
17
15
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
17
15