FactoryBot 为加入 table 生成内容

FactoryBot generate content for join table

我正在尝试使用工厂机器人为 RSpec 生成测试数据。我的表格如下:

User -> 可以是 pro_team_playernoob_team_player 并且有一个模型 conversation 这样:

class Conversation < ActiveRecord::Base
  has_many :messages
  belongs_to :pro_team_player
  belongs_to :noob_team_player
end

所以每个对话都属于一个 pro_team_player 和一个 noob_team_player,每个 conversation 都有许多与之关联的消息。

现在我有 userpro_team_playernoob_team_playermessages 的工厂:

FactoryBot.define do
  factory :user do
    sequence(:name) { |n| "Cool Player#{n}" }
    sequence(:email) { |n| "user#{n}@email.com" }
  end
end

FactoryBot.define do
  factory :pro_team_player do
    player_type 'some type'
    user
  end
end

FactoryBot.define do
  factory :noob_team_player do
    player_type 'some type'
    user
  end
end

FactoryBot.define do
  factory :messages do
    content 'Hola! This is a message'
  end
end

现在我可以将以上数据生成为:

user1 = FactoryBot.create(:user)
pro_team_player = build(:pro_team_player)
user1 = pro_team_player.user1

user2 = FactoryBot.create(:user)
noob_team_player = build(:pro_team_player)
user2 = noob_team_player.user2

我仍在学习 FactoryBot,我不知道如何创建 conversation 工厂或为其生成数据。任何帮助将不胜感激

你走在正确的轨道上。继续遵循您正在使用的模式:

FactoryBot.define do
  factory :conversation do
    pro_team_player
    noob_team_player
    # Other required conversation attributes, if any
  end
end

FactoryBot.define do
  factory :message do
    conversation
    # Other required message attributes, if any
  end
end