Rails / Rspec - 编写涉及自定义验证和belongs_to关联的规范

时间:2012-02-03 03:36:35

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

我有以下AR has_many,belongs_to relations:

联盟 - >会议 - >分部 - >队

我有一个如下所示的事件模型:

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相关联的最简单方法。

1 个答案:

答案 0 :(得分:3)

您可以存储使用工厂生成的实例,然后显式使用其ID来填充后续工厂的外键。

我在这里创建两个联赛,然后设置两个测试。其中一个赛事有两支球队在同一个联赛中,另一支球队有两支不同联赛的球队。这样我就可以测试事件对象是否正确验证:

describe Event do
  before(:each) do
    @first_league = Factory(:league)
    @second_league = Factory(:league)
  end
  it "should allow the home_team and away_team to be from the same league" do
    home_team = Factory(:team, :league_id => @first_league.id)
    away_team = Factory(:team, :league_id => @first_league.id)
    event = Factory(:event, :home_team_id => home_team.id, :away_team_id => away_team.id)
    event.valid?.should == true
  end
  it "should not allow the home_team and away_team to be from two different leagues" do
    home_team = Factory(:team, :league_id => @first_league.id)
    away_team = Factory(:team, :league_id => @second_league.id)
    event = Factory(:event, :home_team_id => home_team.id, :away_team_id => away_team.id)
    event.valid?.should == false
  end
end