Question

So I seem to be having some difficulties with the has_many associations in Factory_Girl

I have four classes with associations:

  • Aaa has_many bbbs & cccs
  • Bbb belongs_to aaa & ddd
  • Ccc belongs_to aaa & ddd
  • Ddd has_many bbbs & cccs

Here are the classes

spec\factories\aaas.rb

FactoryGirl.define do
  factory :aaa do
  end
end

spec\factories\bbbs.rb

FactoryGirl.define do
  factory :bbb do
    aaa
    ddd
  end
end

spec\factories\cccs.rb

FactoryGirl.define do
  factory :ccc do
    aaa
    ddd
  end
end

spec\factories\ddds.rb

FactoryGirl.define do
  factory :ddd do
  end
end

Here's the test I am running

spec\models\aaa_spec.rb

require 'spec_helper'

describe Aaa do
  it "works" do
    aaa = FactoryGirl.create(:aaa)
    puts aaa
    puts aaa.bbbs # This shows up as [] 
    puts aaa.cccs # This shows up as []
    aaa.bbbs.each {|bbb| puts bbb.ddd} # This is nil 
    aaa.cccs.each {|ccc| puts ccc.ddd} # This is nil 
  end
end

Why isnt aaa.bbbs, aaa.cccs, or the ddds showing up?

Was it helpful?

Solution

Reason is simple: in your factory you haven't created any bbb's or ccc's, so you're in the case of "0 objects" (which is a perfectly legal state of "has many"...

If you also want these objects to be created in your factory, you can add something like

after(:build) do |aaa, evaluator|
  aaa.bbb << build(:bbb)
  aaa.ccc << build(:ccc)
end

to your aaa factory

OTHER TIPS

aaas.rb

FactoryGirl.define do
  factory :aaa do
    after(:create) do |aaa|
      create_list(:bbb, 1, aaa: aaa)
      create_list(:ccc, 1, aaa: aaa)
    end
  end
end

Get rid of the aaa in bbbs.rb and cccs.rb

ddds.rb can remain as is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top