Search code examples
ruby-on-railsrspec-rails

Creating a Factorybot to return instance including associated instances


I am new to Rails and Rspecs. So please bear with my questions if this is juvenile.

I am having two associated factorybots as shown:

specs/factories/table_definition.rb

FactoryBot.define do
  factory :table_definition do
    association :project, factory: :project
    name { 'table_definition' }
  end
end

specs/factories/projects.rb

FactoryBot.define do
  factory :project do
    association :user, factory: :user
    name { 'project_name' }
  end
end

And here is my rspec:

require 'rails_helper'

RSpec.describe TableDefinition, type: :model do
  let(:table_definition) { create(:table_definition, project: project) }
  let(:project) { create(:project, user: user) }
  
  it { }
  it { }
end

As you can see, I am creating the instance for the project separately and linking it with the table_definition variable. I just need the factory bot instance table_definition to have a project associated by default. How can we achieve this?

Actually, there are more than 10 interlinked models in my project and for the sake of simplicity, I have provided only two. I am sure there should be a better way of doing this. Your help is appreciated thanks.

-Santhosh


Solution

  • FactoryBot.define do
      factory :table_definition do
        project
        name { 'table_definition' }
      end
    end
    

    Note that project is the same as association :project, factory: :project

    If you don't care about the associated object you can simply call it create(:table_definition) and the association is created for you. If you do care about the association (e.g your test needs to do something with it) then how you call it in your question is the right way.