FactoryGirl通过与自定义属性的关系来解决问题

时间:2013-09-17 04:44:00

标签: ruby-on-rails-3 factory-bot rspec-rails has-many-through

我很难正确设置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我得到 quantity = 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">

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

1 个答案:

答案 0 :(得分: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)