FactoryGirl – 从多态关联中的另一个工厂检索属性

FactoryGirl – Retrieving attributes from another factory in a polymorphic association

我有一个 Board 属于 Artist。到目前为止,我能够在我的电路板工厂中设置此 多态 关联:

FactoryGirl.define do
  factory :board do
    association :boardable, factory: :artist
    boardable_type "Artist"
  end
end

我在我的实际应用程序中设置的模式要求我的面板的 name 是它所属的艺术家的名字。我尝试做类似的事情:

name boardable.name

但最终出现此错误:

ArgumentError: Trait not registered: boardable

通常在 belongs_to/polymorphic 关联中检索属性的最佳方法是什么?

多态关联不需要在 FactoryGirl 中显式声明 association。以下内容已经过验证并将有效:

FactoryGirl.define do
  factory :board do
    boardable factory: :artist
    name { boardable.name }
  end
end

就你的 Board 的名字而言,确保将属性值括在方括号中,否则 FactoryGirl 可能会将其视为特征 :) 你的 boardable_type 属性=12=] 将自动设置为 boardable 的 class,因此它甚至不需要声明。

您可以使用 before :create。像这样

FactoryGirl.define do
  factory :board do
    ...
    before(:create) do |board, evaluator|
      # create artist factory here to associate board to
      # example below that isn't polymorphic but you get the idea
      FactoryGirl.create(:artist, name: "foo").boards << board
    end
  end
end