LoginSignup
1
1

More than 5 years have passed since last update.

has_many throughで定義した関連テーブルをFactory Girlで呼び出す

Posted at

概要

has_many throughで定義した関連テーブルを、Factory Girlで呼び出したい。
例えば次のmodelを考える。

class Job < ActiveRecord::Base
  has_many :job_details, :dependent => :destroy
  has_many :details, :through => :job_details
end

で、Rspecで呼び出す時は下記のようにjob.detailsで呼び出せるようにする。

job = create(:job)
details = job.details

方法

FactoryGirlを作成する時に下記のように定義すればOK。

factory :job do
  ...

  after_create do |job|
    job.details << FactoryGirl.create(:detail)
  end
end

呼び出し方

detailsを呼び出す。

job = create(:job)
details = job.details

detailsの値を取得する。

job.details.target

detailsの1番目のidを取得する。

job.details[0].id

参考

has_many through with Factory Girl

1
1
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
1