Factory_bot,如何在 child 属于 parent 和 parent 的关系中重用 parent 工厂 parent?

Factory_bot, how to reuse parent factory in relationship where child belongs to both parent and parents parent?

Shift belongs_to EmployeeSite 同时 Employee belongs_to Site

鉴于此,这里有一个工厂:

  factory :site do
    ...
  end
  
  factory :employee do
    site
    ...
  end

  factory :shift do
    employee # creates a site
    site # creates a new site; i.e., this is NOT same site as employee site, each call creates a new site
    ...
  end

当我 运行 create(:shift) 时,我希望默认创建的 shift.siteshift.employee.site 相同,但目前的行为是 2 个站点已创建,当我只想要一个时。

谢谢,

您可以访问 Factory Bot 中已经定义的字段。所以这有效,

  factory :site do
    ...
  end
  
  factory :employee do
    site
    ...
  end

  factory :shift do
    employee # creates a site
    site { employee.site }
    ...
  end