【发布时间】:2012-02-03 03:36:35
【问题描述】:
我有以下 AR has_many,belongs_to 关系:
联赛 --> 会议 --> 分区 --> 团队
我有一个看起来像这样的事件模型:
class Event < ActiveRecord::Base
belongs_to :league
belongs_to :home_team, :class_name => 'Team', :foreign_key => :home_team_id
belongs_to :away_team, :class_name => 'Team', :foreign_key => :away_team_id
validate :same_league
def same_league
return if home_team.blank? || away_team.blank?
errors.add :base, "teams must be in the same league" if home_team.league != away_team.league
end
end
还有一些工厂:
FactoryGirl.define do
factory :league do
name 'NFL'
end
end
Factory.define :conference do |f|
f.name 'NFC'
f.association :league
end
Factory.define :division do |f|
f.name 'North'
f.association :conference
end
Factory.define :team do |f|
f.name 'Packers'
f.locale 'Green Bay'
f.association :division
end
FactoryGirl.define do
factory :event do
association :league
association :home_team, :factory => :team
association :away_team, :factory => :team
end
end
那么,我将如何为 same_league 验证方法编写规范?
describe Event do
pending 'should not allow home_team and away_team to be from two different leagues'
end
我的问题是知道在赛事模型中创建两支不同联赛的球队并将一支与 home_team 和另一支与 away_team 相关联的最简单方法。
【问题讨论】:
标签: ruby-on-rails factory-bot rspec-rails