2013-03-17 75 views
0

我想使用FactoryGirl创建一个自我关联的对象,用于测试类别的简单树。我已阅读FactoryGirl's Getting Started doc设置关联,但仍有问题。我想测试一个对象有父母和孩子(因为这是我的FactoryGirl定义中的设置,所以有一个孩子)。我给父测试通过,但对测试失败用于儿童FactoryGirl测试失败 - 试图建立一个自己的协会

ERROR消息

1) Category should have a child 
    Failure/Error: category.children.count.should eq(1) 

    expected: 1 
      got: 0 

RSPEC测试

it "should have a child" do 
    category = FactoryGirl.build(:parent_category) 

    category.should_not be_nil 

    category.children.count.should eq(1) 
end 

it "should have a parent" do 
    category = FactoryGirl.build(:child_category) 

    category.should_not be_nil 

    category.parent.should_not be_nil 
end 

模型设置用于父/子关系(同一模型的) :

class Category < ActiveRecord::Base 
    include ActiveModel::ForbiddenAttributesProtection 

    belongs_to :parent, :class_name => 'Category' 
    has_many :children, :class_name => 'Category', :foreign_key => 'parent_id', :dependent => :destroy 

    attr_accessible :name, :parent_id 

    validates :name, :presence => true 

    before_validation :uppercase_name 

    def uppercase_name 
    self.name.upcase! unless self.name.nil? 
    end 
end 

FACTORYGIRL设置:

FactoryGirl.define do 
    factory :category do 
    name "CATEGORY" 

    factory :parent_category do 
     name "PARENT" 
     parent_id 0 
     after(:create) do |pc, evaluator| 
     FactoryGirl.create_list(:category, 1, parent: pc) 
     end 
    end 

    factory :child_category do 
     name "CHILD" 
     association :parent, factory: :parent_category 
    end 

    end 
end 

回答

1

我们结束了使用closure_tree 因为与awesome_nested_set

的并发问题