FactoryGirlのassociationをつけなくてもモデル間を関連づけする方法

FactoryGirlでモデルの関連づけをする場合は、associationを使ったりします。

ただし、なんでもassociationを使うと、テストが多くなるにつれて、テストが壊れやすくなります。

関連づけをする書き方は他にもあります。

associationのあり/なしの書き方を見せます。

書き方

まずは下記のようなモデルがあったとします。

class Contact < ActiveRecord::Base
  has_many :phones
end

class Phone < ActiveRecord::Base
  belongs_to :contact
end

associationで書く場合 /spec/factory/

FactoryGirl.define do
  factory :contact do
    firstname 'John'
    lastname 'Doe'
    sequence(:email) { |n| "johndoe#{n}@example.com" }
  end
end

FactoryGirl.define do
  factory :phone do
    association :contact
    phone '123-555-1234'
    phone_type 'home'
  end
end

/spec/models/

  it "allows two contacts to share a phone number" do
    create(:phone)
  end

pry(#<RSpec::ExampleGroups::Phone>)> Phone.all
=> [#<Phone id: 1, contact_id: 1, phone: "123-555-1234", phone_type: "home", created_at: "2016-05-15 09:42:44", updated_at: "2016-05-15 09:42:44">]

関連づけされています。

associationなしの場合 /spec/factory/

FactoryGirl.define do
  factory :contact do
    firstname 'John'
    lastname 'Doe'
    sequence(:email) { |n| "johndoe#{n}@example.com" }
  end
end

FactoryGirl.define do
  factory :phone do
    phone '123-555-1234'
    phone_type 'home'
  end
end

/spec/models/

  it "allows two contacts to share a phone number" do
    contact = create(:contact)
    create(:phone, contact: contact)
  end

→=>pry(#<RSpec::ExampleGroups::Phone>)> Phone.all
=> [#<Phone id: 1, contact_id: 1, phone: "123-555-1234", phone_type: "home", created_at: "2016-05-15 09:41:04", updated_at: "2016-05-15 09:41:04">]

無事に関連づけが行われています。

まとめ

無理してassociationを書かなくても大丈夫です。