1

我很难正确设置这个 FactoryGirl 关联。

我的模型如下:

class ProductList < ActiveRecord::Base  
  has_many :product_list_items   
  has_many :product_variations, :through => :product_list_items
end

class ProductVariation < ActiveRecord::Base    
  has_many :product_list_items
  has_many :product_lists, :through => :product_list_items
end

class ProductListItem < ActiveRecord::Base
  attr_accessible :product_list_id, :product_variation_id, :quantity

  belongs_to :list
  belongs_to :product_variation
end

我的工厂如下:

FactoryGirl.define do
  factory :product_list do
    sequence(:name) { |n| "Product List {n}" }
    description "Product List Description"
    user    
    after :create do |p|
      p.product_variations << FactoryGirl.create(:product_variation)
    end
  end
end

FactoryGirl.define do
  factory :product_list_item do
    association :product_list
    association :product_variation
    quantity { rand(1..30) }
  end
end

FactoryGirl.define do
  factory :product_variation do
    sequence(:sku) { |n| "product_sku_#{n}" }
    product
    price {"#{ rand(1..30) }.#{ rand(10..99) }"}
    currency "USD"
  end
end        

现在,当我将产品列表工厂创建为

product_list = FactoryGirl.create(:product_list)  

并检查 product_list_item 的 product_list 我得到数量 = nil

product_list.product_list_items.first.inspect

#<ProductListItem id: 8, product_list_id: 8, product_variation_id: 8, quantity: nil, created_at: "2013-09-17 04:35:58", updated_at: "2013-09-17 04:35:58">

有人可以指出我哪里出错了吗?提前致谢。

4

1 回答 1

0

应该可以create_list结合评估器访问的瞬态属性来构建多个自定义记录,如下所示:

FactoryGirl.define do
  factory :post do
    sequence(:title) { |n| "a title #{n}" }

    factory :post_with_comments do
      transient do
        comments %w(fantastic awesome great)
      end

      after(:create) do |post, evaluator|
        FactoryGirl.create_list(:comment, evaluator.comments.count, post: post) do |instance|
          instance.text = evaluator.comments.shift
        end
      end
    end
  end
end

(或pop代替shift相反的顺序),可以称为

title = 'Post Title'
names = %w(well wtf crap)
model = FactoryGirl.create(:post_with_comments, title: title, comments: names.clone) 
于 2015-07-16T15:47:51.500 回答