当尝试使用 FactoryGirl 初始化数据时,我遇到了一个问题,无法访问我之前创建的数据。
假设我有 3 个不同的模型:Product、CartItem 和 OrderItem。这些是基本规则:
- CartItem 和 OrderItem 属于 Product,并且是必需的。
- 产品具有唯一标识符“名称”。
我的工厂文件是这样设置的:
产品
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 实例,因为我使用此 Product.find_by("A Product") || 设置了 OrderItem 的产品FactoryGirl.create(:product)
应该首先尝试在创建新产品实例之前找到该产品实例。
关于为什么会发生这种情况有什么想法吗?
最佳答案
已更新
我认为您的问题出在您使用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)
关于ruby-on-rails - FactoryGirl 在数据库中找不到实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44168368/