Home > Mobile >  How to solve the ActiveRecord::RecordInvalid error when creating a factory?
How to solve the ActiveRecord::RecordInvalid error when creating a factory?

Time:04-08

I have a model

class Income < ApplicationRecord

  belongs_to :income_type
  has_one :order

  validates_associated :income_type
  validates_presence_of :income_type

I create a factory for her

FactoryBot.define do
  factory :income do
    income_type
    amount { 100.0 }
  end
end

But it doesn't work and throws an error

Failure/Error: let!(:income) { create(:income) }

     ActiveRecord::RecordInvalid: Error

CodePudding user response:

I believe it happens due to validation of income_type. If you have a factory for income_type. You can do it two ways. Provide income_type directly

let(:income_type) { create(:income_type) }
let!(:income) { create(:income, income_type: income_type) }

or define an association inside the income factory.

FactoryBot.define do
  factory :income do
    association(:income_type)
    amount { 100.0 }
  end
end
  • Related