查询关于使用 FactoryBot 创建 has_many & belongs_to 记录
query about create has_many & belongs_to records using FactoryBot
我正在写 Rspec requests spec
,在此之前我想使用 FactoryBot
.
构建一些测试数据
现在我有一个模型 Game
:
class Game < ApplicationRecord
has_many :game_levels
和一个模型GameLevel
:
class GameLevel < ApplicationRecord
belongs_to :game
在我的/spec/factories/game.rb
中:
FactoryBot.define do
factory :game do
name { :Mario }
end
end
在我的 spec/factories/game_level.rb
:
FactoryBot.define do
factory :game_level do
name { :default }
min_level { 0 }
max_level { 100 }
game
end
end
在我的spec/requests/user_plays_game_spec.rb
中,我只是简单地编写了创建游戏的代码&game_level,并打印了game.id
、game_level.game_id
。我发现他们不一样。此外,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
那么如何使用 FactoryBot
将 belongs_to
记录关联到 has_many
记录?
创建时可以关联
@game = create(:game)
@game_level = create(:game_level, game: @game)
工厂中的关联很直观:
FactoryBot.define do
factory :template do
template_category { create(:template_category) }
end
end
没什么特别的。如果它不适合你,你可能有配置问题。
我正在写 Rspec requests spec
,在此之前我想使用 FactoryBot
.
现在我有一个模型 Game
:
class Game < ApplicationRecord
has_many :game_levels
和一个模型GameLevel
:
class GameLevel < ApplicationRecord
belongs_to :game
在我的/spec/factories/game.rb
中:
FactoryBot.define do
factory :game do
name { :Mario }
end
end
在我的 spec/factories/game_level.rb
:
FactoryBot.define do
factory :game_level do
name { :default }
min_level { 0 }
max_level { 100 }
game
end
end
在我的spec/requests/user_plays_game_spec.rb
中,我只是简单地编写了创建游戏的代码&game_level,并打印了game.id
、game_level.game_id
。我发现他们不一样。此外,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
那么如何使用 FactoryBot
将 belongs_to
记录关联到 has_many
记录?
创建时可以关联
@game = create(:game)
@game_level = create(:game_level, game: @game)
工厂中的关联很直观:
FactoryBot.define do
factory :template do
template_category { create(:template_category) }
end
end
没什么特别的。如果它不适合你,你可能有配置问题。