代码之家  ›  专栏  ›  技术社区  ›  timpone

factory-bot/factory-girl添加所属对象的语法

  •  0
  • timpone  · 技术社区  · 6 年前

    我有以下型号:

    class SecondaryIabCategory < ApplicationRecord
      has_many :sites, foreign_key: :secondary_category_id
      belongs_to :primary_iab_category
    end
    

    并对以下工厂的问题进行了评论:

      factory :primary_category, class: PrimaryIabCategory do
        name 'Arts & Entertainment - yaddah'
        value 'IAB1-some'
      end
    
      factory :another_primary_category, class: PrimaryIabCategory do
        name 'Games are cool! - dabbah'
        value 'IAB1-other'
      end
    
      factory :secondary_category, class:  SecondaryIabCategory do
        # here is the problem - what's the correct syntax?
        primary_iab_category another_primary_category
        name 'Test Secondary Cat'
        value 'xxyy'
      end
    

    我得到错误消息:

    NoMethodError: undefined method `another_primary_category=' for #<SecondaryIabCategory:0x00007f925c64e0d8>
    

    我已经有几个月没有使用factrybot/girl了,所以不知道它的语法是什么。有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   kasperite    6 年前

    试试这个

    factory :secondary_category, class:  SecondaryIabCategory do
      association :primary_iab_category, factory: :another_primary_category
      name 'Test Secondary Cat'
      value 'xxyy'
    end
    

    这个 rubydoc 是相当详细的