FactoryGirl无法在DB

时间:2017-05-24 21:00:10

标签: ruby-on-rails ruby testing factory-bot minitest

当尝试使用FactoryGirl初始化数据时,我遇到了能够访问我创建的先前数据的问题。

假设我有3种不同的型号:Product,CartItem和OrderItem。这些是基本规则:

  • CartItem和OrderItem belongs_to Product,是必需的。
  • 产品具有唯一标识符'name'。

我的工厂文件设置如下:

产品

FactoryGirl.define do
  factory :product do
    name "A Product"
  end
end

CartItem

FactoryGirl.define do
  factory :cart_item do
    association :product do
        Product.find_by(name: "A Product") || FactoryGirl.create(:product)
    end
  end
end

OrderItem的

FactoryGirl.define do
  factory :order_item do
    association :product do
        Product.find_by(name: "A Product") || FactoryGirl.create(:product)
    end
  end
end

现在,在一次测试中,我首先使用此调用FactoryGirl.create(:cart_item)

创建CartItem

一切都运行良好。因为没有Product,所以会创建一个新的,然后将其分配给CartItem。

接下来,我尝试使用此调用FactoryGirl.create(:order_item)

创建OrderItem

这次运行时,它失败并显示错误Validation failed, Name has already been taken

尝试创建名为“A Product”的新产品时失败,该产品已从创建CartItem的调用中创建。

但是,这甚至不应该尝试创建新的Product实例,因为我使用此Product.find_by("A Product") || FactoryGirl.create(:product)设置OrderItem的产品,该产品应首先尝试在创建新产品实例之前找到该产品实例。

有关为何发生这种情况的任何想法?

2 个答案:

答案 0 :(得分:1)

<强>更新

我认为您的问题与您使用association的方式有关。我不会在任何地方看到关联会像你定义它一样阻塞。

您想要做的事情就是这样

factory :cart_item do
  product { Product.find_by(name: "A Product") || association(:product) }       
end

这实际上似乎是错误的,因为你创造了非决定论。相反,您应该创建一条记录并在测试中将其直接分配给工厂。

FactoryGirl.define do
  factory :cart_item do
    association :product 
  end
end

FactoryGirl.define do
  factory :order_item do
    association :product
  end
end

然后在你的测试中

product = FactoryGirl.create(:product)
cart_item = FactoryGirl.create(:cart_item, product: product)
order_item = FactoryGirl.create(:order_item, product: product)

答案 1 :(得分:0)

这只是一个想法,但尝试在FactoryGirl配置中注释掉FactoryGirl.lint。

相关问题