FactoryBot为连接表生成内容

时间:2018-02-23 18:45:06

标签: ruby-on-rails activerecord factory-bot factory

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

User - >可以是pro_team_playernoob_team_player,还有一个模型conversation,以便:{/ p>

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

因此,每个对话都属于pro_team_playernoob_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工厂或为其生成数据。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

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

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