使用FactoryGirl的has_many关系

时间:2017-01-04 12:39:43

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord factory-bot

我尝试使用FactoryGirl工厂创建has_many关系的实例并失败。 我有两个类:计算机和网卡。每台计算机都可以有许多网卡。

定义了两个ActiveRecords:

1

class Computer < ActiveRecord::Base
  has_many :network_cards
end

2

class Article < ActiveRecord::Base
  belongs_to: computer
end

定义了以下工厂:

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

现在,在RSpec测试中创建计算机时,我得到了一个我无法解释的奇怪行为。

@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

任何想法我都缺少什么?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

试试这个:

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