FactoryGirl 在数据库中找不到实例

FactoryGirl not finding instances in DB

当尝试使用 FactoryGirl 初始化数据时,我 运行 遇到了一个问题,无法访问我之前创建的数据。

假设我有 3 个不同的模型:Product、CartItem 和 OrderItem。这些是基本规则:

我的工厂文件是这样设置的:

产品

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

购物车商品

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

订单项

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

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

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

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

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

尝试创建名为 "A Product" 的新产品时失败,该产品已通过调用创建 CartItem 创建。

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

关于为什么会发生这种情况的任何想法?

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

已更新

我认为您的问题出在您使用 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)