0

I have the following factory:

factory :store do
  room
  factory :store_with_items do
    ignore do
      items_count 4
    end

    after(:create) do |store, evaluator|
      FactoryGirl.create_list(:equippable_item, evaluator.items_count, store: store)
    end
  end
end

Next, I create an object:

@store = FactoryGirl.create :store_with_items

My problem is that when I "delete" one of the store's items, the store still shows that it has 4 items.

@store.items[0].store_id = nil
@store.save!
puts @store.items.size

The puts is 4. How do I properly delete an item? Isn't this how you would do it in rails?

4

1 回答 1

0

我以前更喜欢这种方法,但现在我避免了;让工厂变得简单并在运行时填充 has_many 关联更容易、更灵活。

尝试这个

商店工厂(相同):

factory :store do
  room
end

项目工厂:

factory :item do
  store # will use the store factory
end

然后在我的测试中,我将填充适合手头案例的内容:

@store = FactoryGirl.create :store
@item1 = FactoryGirl.create :item, store: @store
@item2 = FactoryGirl.create :equippable_item_or_whatever_factory_i_use, store: @store

解释

通过显式传入 store 实例,将为您设置关联。这是因为当您显式传入某些内容FactoryGirl.createFactoryGirl.build它会覆盖工厂定义中定义的任何内容时。它甚至适用于零。这样,您将拥有为您提供所有真实功能的真实对象实例。

测试破坏

我认为您示例中的代码不好;它破坏了商店和商品之间的关联,但实际上并没有删除商品记录,因此您留下了孤儿记录。我会这样做:

@store.items[0].destroy
puts @store.items.size

奖金

您可能还希望将您的子关联设置为在父级被销毁时被销毁(如果尚未销毁)。这意味着当您说@store.destroy属于它的所有项目也将被销毁(从数据库中删除。)

class Store < ActiveRecord::Base
  has_many :items, dependent: :destroy
  .....
end
于 2013-02-08T08:03:48.037 回答