Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: Factory definition for associated object

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
like image 447
Rajkaran Mishra Avatar asked Nov 24 '19 21:11

Rajkaran Mishra


Video Answer


1 Answers

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.

like image 162
Grzegorz Avatar answered Nov 07 '22 12:11

Grzegorz