FactoryBot如何为相互关联的模型创建工厂

时间:2018-10-22 10:30:08

标签: ruby-on-rails rspec factory-bot

我正在尝试为旧版ROR应用编写RSpec测试。我有以下型号

class Domain < ActiveRecord::Base
  belongs to :account
  ...
end
class Account < ActiveRecord::Base
  belongs to :domain
  ...
end

FactoryBot.define do
  factory :domain do
    name 'domain-1'
    account { association :account, domain: @instance }
  end
end
FactoryBot.define do
  factory :account do
    name 'account-1'
    domain { association :domain, account: @instance }
  end
end

我可以创建

FactoryBot.create(:domain) 但是FactoryBot.create(:account)失败,并且Domain不能为空

1 个答案:

答案 0 :(得分:2)

在通常情况下,帐户和域具有一对多关系。因此每个域都有一个帐户,一个帐户可以有多个域。

class Domain < ActiveRecord::Base
  belongs_to :account
  ...
end
class Account < ActiveRecord::Base
  has_many :domains
  ...
end

您的工厂相互递归调用。它应该工作:

FactoryBot.define do
  factory :domain do
    name 'domain-1'
    account
  end
end
FactoryBot.define do
  factory :account do
    name 'account-1'
  end
end