Question: has_many relationship using FactoryGirl

Question

has_many relationship using FactoryGirl

Answers 2
Added at 2017-01-04 13:01
Tags
Question

I'm trying to create instance with has_many relationship using FactoryGirl factories and fail. I have two classes: Computers and NetworkCards. Each Computer can have many NetworkCards.

Defined two ActiveRecords:

1.

class Computer < ActiveRecord::Base
  has_many :network_cards
end

2.

class Article < ActiveRecord::Base
  belongs_to: computer
end

Defined the following factories:

1.

factory :computer do
  sequence(:name) { |n| "PC_#{n}" }
  transient do
    network_cards_count 1
  end

  after(:create) do |computer|
    create_list(:network_card, evaluator.network_cards_count, computer: computer)
  done
end

2.

factory :network_card do
  sequence(:name) { |n| "NC_#{n}" }
  sequence(:type) { |n| "TYPE_#{n}" }
end

Now, when creating a computer in a RSpec test I get a weird behavior I can't explain.

@computer_1 = FactoryGirl.create(:computer)
@computer_1.network_cards.size #Expect 1. Got 0. Why?
@computer_1.reload
@computer_1.network_cards.size # Got 1

Any ideas what am I missing?

Answers
nr: #1 dodano: 2017-01-04 16:01
factory :computer do
  sequence(:name) { |n| "PC_#{n}" }
  transient do
    network_cards_count 1
  end

  after(:create) do |computer, evaluator|
    create_list(:network_card, evaluator.network_cards_count, computer: computer)
    computer.reload #<----- solves the issue
  end
end
nr: #2 dodano: 2017-01-04 18:01

Try this:

 after(:build) do |computer, evaluator|
      computer.network_cards << build_list(:network_card, evaluator.network_cards_count, computer: computer)
 end
Source Show
◀ Wstecz