【问题标题】:FactoryGirl Test Failure - Trying to Build an Association to ItselfFactoryGirl 测试失败 - 试图建立自己的关联
【发布时间】:2013-03-17 19:55:08
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails-3.2 factory-bot rspec-rails


    【解决方案1】:

    我们最终使用了closure_tree 因为 awesome_nested_set 的并发问题

    【讨论】:

      【解决方案2】:

      我发现了一个很有前途的宝石,名为 awesome_nested_set,它似乎有一个非常干燥的目的。

      还有一个有趣的树宝石,叫做ancestry

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多