Search code examples
ruby-on-railsfactory-bothas-manybelongs-to

query about create has_many & belongs_to records using FactoryBot


I am writing Rspec requests spec, and before it I want to build some test data using FactoryBot.

And now I have a model Game:

class Game < ApplicationRecord
  has_many :game_levels

and a model GameLevel:

class GameLevel < ApplicationRecord
  belongs_to :game

In my /spec/factories/game.rb:

FactoryBot.define do
  factory :game do
    name { :Mario }
  end
end

In my spec/factories/game_level.rb:

FactoryBot.define do
  factory :game_level do
    name { :default }
    min_level { 0 }
    max_level { 100 }

    game
  end
end

In my spec/requests/user_plays_game_spec.rb, I simply wrote code to create game & game_level, and printed game.id, game_level.game_id. I found they are not the same. besides, game.game_levels returns nil.

before(:all) do
  @game = create(:game)
  @game_level = create(:game_level)
end

describe do
  it do
    puts @game,id, @game_level.game_id
    puts @game.game_levels

    expect(@game.id).to eql(@game_level.game_id)
  end
end

So how do I associate a belongs_to record to a has_many record using FactoryBot?


Solution

  • You can associate it during the create

    @game = create(:game)
    @game_level = create(:game_level, game: @game)