【问题标题】:FactoryBot generate content for join tableFactoryBot 为连接表生成内容
【发布时间】:2018-02-23 18:45:06
【问题描述】:

我正在尝试使用工厂机器人为 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_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 工厂或为此生成数据。任何帮助将不胜感激

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-16
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 2013-01-30
      相关资源
      最近更新 更多