I have the following three models: Product
, Warehouse
and 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
I have this factory for Inventory:
FactoryBot.define do
factory :inventory do
product { nil }
warehouse { nil }
item_count { 1 }
low_item_threshold { 1 }
end
end
How can I use this factory for Inventory or what changes are needed in my other factories so that I can have a spec something like this?
RSpec.describe Inventory, type: :model do
it "has a valid factory" do
expect(FactoryBot.build(:inventory)).to be_valid
end
end
What you need is to change the :inventory
factory definition, like this
FactoryBot.define do
factory :inventory do
product
warehouse
item_count { 1 }
low_item_threshold { 1 }
end
end
This will "tell" factory bot to instantiate the associated objects (https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#associations)
But for this to work, you need to define warehouse
and product
factories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With