4
我有以下AR的has_many,belongs_to的關係:軌道/ Rspec的 - 書寫規範,涉及自定義驗證和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
所以,所有這一切,我會怎麼去寫一個spec的same_league驗證方法?
我的問題是知道什麼是最簡單的方式去創造不同的聯賽兩隊關聯一個與HOME_TEAM和其他與事件模型AWAY_TEAM。
嘿Baldrick - 我的解決方案是否適合您? – 2012-02-14 06:40:27