ruby-on-rails - FactoryGirl 在数据库中找不到实例

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

当尝试使用 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/

相关文章:

ruby - 如何将每个语句的结果输​​出到变量?

testing - 寻找英文文本以测试用户可能的输入

ruby-on-rails - spec 和 test 文件夹之间的区别

ruby-on-rails - ActiveRecord::RecordInvalid:验证失败:用户必须存在

ruby-on-rails - 构建多页表单以在数据库中创建和编辑模型的最佳方法是什么?

Ruby - 哈希 - 组合

python-2.7 - 我想将一个模块从 Python 2 移植到 3,如何运行测试?

ruby-on-rails - Ocra 生成的 exe 不接受参数

ruby-on-rails - Rails HTML5 离线数据库

ruby - MongoDB、Ruby 不显示id 字段?