【发布时间】:2018-02-23 18:45:06
【问题描述】:
我正在尝试使用工厂机器人为 RSpec 生成测试数据。我的表格如下:
User -> 可以是pro_team_player 或noob_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 都有许多与之关联的消息。
现在我有 user、pro_team_player、noob_team_player 和 messages 的工厂:
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