has_many 关系使用 FactoryGirl

has_many relationship using FactoryGirl

我正在尝试使用 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

知道我错过了什么吗?

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

试试这个:

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