Search code examples
ruby-on-railsactiverecordfactory-bot

Why i am getting this error in Factory: must be exist card? how can i solved it?


Only i want to create a 'post' but i am getting this error:

Failure/Error: let!(:post) { FactoryBot.create(:post, company_id: company.id, card_id: card.id) } 
ActiveRecord::RecordInvalid:
        Validation failed: must be exist card

the model of post is:

class Post < ApplicationRecord
  validates :first_title, :sub_title, :email, presence: true
  belongs_to :card
  delegate :max, to: :card
end

and card:

class Card < ApplicationRecord
  include Discard::Model
end

factories:

factory :post do
    first_title { Faker::Name.name }
    sub_title { Faker::Name.name }
    email { Faker::Internet.email}
    card_id {}
  end

factory for card:

factory :card do
  company_id {}
end

Solution

  • Compiling the response from the other question:

    factory :card do
      association :company, factory: :company
    end
    
    factory :post do
      first_title { Faker::Name.name }
      sub_title { Faker::Name.name }
      email { Faker::Internet.email}
    
      transient do
        company_id { FactoryBot.create(:company).id }
      end
    
      after(:build) do |post, evaluator|
        card = FactoryBot.create(:card, company_id: evaluator.company_id)
        post.card = card
      end
    end
    
    let(:company) { FactoryBot.create :company }
    let!(:post) { FactoryBot.create(:post, company_id: company.id }
    let(:card) { post.card }