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

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

我有以下 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 关​​联的最简单方法是什么。

最佳答案

您可以存储使用工厂生成的实例,然后显式使用它们的 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

关于ruby-on-rails - Rails/Rspec - 编写涉及自定义验证和belongs_to 关联的规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9123335/

相关文章:

ruby-on-rails-3 - 在 Rails 3.1 中使用 Capybara、Rspec 和 Selenium 进行测试时登录失败

ruby-on-rails - capybara 不和工厂女工一起工作

ruby-on-rails-4 - 运行 rspec 时未初始化的常量 FactoryGirl,但在控制台中工作

ruby-on-rails - RSpec : failure Cabybara Webkit InvalidResponseError

ruby-on-rails - 如何在 RSpec 中测试 send_data?或者……在这种情况下我应该测试什么?

ruby-on-rails - 创建新的Rails Action 行不通吗?

ruby-on-rails - Rails - 充当嵌套 - 不可能移动,目标节点不能位于移动的树内

ruby-on-rails - authlogic - session 创建失败的原因并且没有错误消息(使用 formtastic)

ruby-on-rails - 参数错误 : SMTP To address may not be blank: []