如何通过 join table with FactoryGirl 将属性值传递给 has_many?

How do you pass an attribute value to the has_many through join table with FactoryGirl?

food.rb工厂:

FactoryGirl.define do
  factory :food do
    factory :apple do
      description 'apple'
      sequence(:name) { |n| "apple #{n}"}
      long_description 'Apple'
    end

    factory :burger do
      description 'burger'
      sequence(:name) { |n| "burger #{n}"}
      long_description 'Burger'
    end

    after(:create) do |food|
      [:fat, :protein, :carb, :fiber].each do |nutrient|
        food.nutrients << FactoryGirl.create(nutrient, :measurement)
      end
    end
  end
end

nutrient.rb工厂

FactoryGirl.define do
  factory :nutrient do
    factory :fat do
      name 'Fat'
      slug 'fat'
    end

    factory :protein do
      name 'Protein'
      slug 'protein'
    end

    factory :carb do
      name 'Carbohydrates'
      slug 'carbohydrates'
    end

    factory :fiber do
      name 'Fiber'
      slug 'fiber'
    end

    trait :measurement do
      measurement 'milligrams'
    end
  end
end

食品_nutrient.rb工厂

FactoryGirl.define do
  factory :food_nutrient do
    food
    nutrient
    qty rand(1..100)
  end
end

功能测试:

feature 'Search' do
  scenario 'for apples' do
    user = FactoryGirl.create(:user)
    apples  = 15.times.map { FactoryGirl.create(:apple) }
    burgers = 5.times.map { FactoryGirl.create(:burger) }

    ...more code
  end
end

我得到的错误是: Failure/Error: 苹果 = 15.times.map { FactoryGirl.create(:apple) } ActiveRecord::RecordInvalid: 验证失败:数量不能为空

Qty 是 food_nutrient has_many 中的一个属性:到 join_table。我如何传递那个变量?

您需要在 after(:create) 中添加 FoodNutrient 个实例,而不是直接添加营养素:

after(:create) do |food|
  [:fat, :protein, :carb, :fiber].each do |nutrient|
    food.food_nutrients << FactoryGirl.create(:food_nutrient, 
      nutrient: FactoryGirl.create(:nutrient, :measurement)
    )
  end
end

这将使用您的 food_nutrient 工厂创建与四种营养素中的每一种相关联的 FoodNutrient 实例。