我有以下三个型号:Product
, Warehouse
和 Inventory
# 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
最佳答案
您需要的是更改:inventory
工厂定义,像这样
FactoryBot.define do
factory :inventory do
product
warehouse
item_count { 1 }
low_item_threshold { 1 }
end
end
这将“告诉”工厂机器人实例化关联的对象( https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#associations )但要使其正常工作,您需要定义
warehouse
和 product
工厂。
关于ruby-on-rails - RSpec:关联对象的工厂定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022462/