Question

I'm attempting to print factory bbb_a.

I have two models

  • aaa has_many bbbs
  • bbb belongs_to aaa

aaas.rb

FactoryGirl.define do
  factory :aaa do
    after(:build) do |aaa|
      aaa.bbbs << build(:bbb_a)
      aaa.bbbs << build(:bbb_b)
    end
  end
end

bbbs.rb

FactoryGirl.define do
  factory :bbb do
    factory :bbb_a do
    end
    factory :bbb_b do
    end
  end
end

aaa_spec.rb

require 'spec_helper'
describe Aaa do
  it "works" do
    aaa = FactoryGirl.create(:aaa)
    puts aaa.bbbs(:bbb_a) #This gives both bbb_a and bbb_b
    aaa.should_not be_nil
  end
end

Console Output

Bbb 1
Bbb 2
.

Finished in 0.11593 seconds
1 example, 0 failures

Randomized with seed 44359

What I Expected

Bbb 1
.

Finished in 0.11593 seconds
1 example, 0 failures

Randomized with seed 44359

Why is it that it puts both bbb_a and bbb_b? How can I get it to just print bbb_a?

Was it helpful?

Solution

All you have to do is to replace

puts aaa.bbbs(:bbb_a)

With either

puts aaa.bbbs.first

Or

puts aaa.bbbs[0]

Because you have a has_many relationship between Aaa and Bbb models, rails creates dynamic instance methods for you as Aaa#bbbs and Bbb#aaa. This method accept 0 or 1 arguments. If you pass an argument to this method as true then it fires the query on the database to retrieve the associated records. And If you pass an argument to this method as false then it just picks up the cached results of the query (provided query was fired once before for the caching to take place).

So, when you do

puts aaa.bbbs(:bbb_a)

The value passed is simply ignored as its neither true or false.

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