RSpec:关联对象的工厂定义

问题描述 投票:1回答:1

我有以下三种模型:产品,仓库和库存

# app/models/product.rb
class Product < ApplicationRecord
  has_many :inventories
  has_many :warehouses, through: :inventories  
end

# app/models/warehouse.rb
class Warehouse < ApplicationRecord
  has_many :inventories
  has_many :products, through: :inventories
end

# app/models/inventory.rb
class Inventory < ApplicationRecord
  belongs_to :product
  belongs_to :warehouse
end

我有这个库存工厂:

FactoryBot.define do
  factory :inventory do
    product { nil }
    warehouse { nil }
    item_count { 1 }
    low_item_threshold { 1 }
  end
end

我如何使用该工厂进行库存,或者在其他工厂中需要进行哪些更改,以便获得类似这样的规格?

RSpec.describe Inventory, type: :model do
  it "has a valid factory" do
   expect(FactoryBot.build(:inventory)).to be_valid
  end
end
ruby-on-rails rspec factory-bot
1个回答
0
投票
FactoryBot.define do
  factory :inventory do
    product
    wharehouse
  end
end

库存工厂可以简单地定义为。当您具有模型中陈述的关系时,应该没有问题。

[productwarehouse被考虑为库存所属的关系。

© www.soinside.com 2019 - 2024. All rights reserved.