代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

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

  •  1
  • Carl Edwards monkbroc  · 技术社区  · 10 年前

    我有一个 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 协会

    2 回复  |  直到 10 年前
        1
  •  0
  •   Collin Graves    10 年前

    多态关联不需要显式 association 在FactoryGirl申报。以下内容已验证并将有效:

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

    就你的 Board 的名称,请确保将属性值括在括号中,否则FactoryGirl可能会将其视为特征:) boardable_type 您的属性 将自动设置为 boardable 的类,所以它甚至不需要声明。

        2
  •  0
  •   MilesStanfield    10 年前

    您可以使用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