我正在尝试使用 FactoryGirl 创建一个自关联对象以用于测试简单的类别树。我已通读FactoryGirl 的入门文档以设置关联,但仍有问题。我想测试一个对象是否有父对象和子对象(1 个子对象,因为这是我的 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