我正在尝试使用FactoryGirl创建一个自关联对象,用于测试一个简单的类别树。我已阅读FactoryGirl's Getting Started doc来设置关联,但仍有问题。我想测试一个对象有一个父对象和一个孩子(因为那是我的FactoryGirl定义中的设置,所以有一个孩子)。我对父母的测试通过,但未能测试孩子
错误消息
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
答案 0 :(得分:1)
我们最终使用closure_tree 因为awesome_nested_set的并发问题
答案 1 :(得分:0)
我发现了一种名为awesome_nested_set的有前途的宝石,它看起来非常干净。
另一个有趣的树宝石叫ancestry。