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

ruby-on-rails – RailsRspec – 编写涉及自定义验证和belongs_to关联的规范,第1张

概述我有以下AR has_many,belongs_to关系: 联赛 – >会议 – >分部 – >球队 我有一个看起来像这样的事件模型: class Event < ActiveRecord::Base belongs_to :league belongs_to :home_team, :class_name => 'Team', :foreign_key => :home_team_id 我有以下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,: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  endend

还有一些工厂:

FactoryGirl.define do  factory :league do    name 'NFL'  endendFactory.define :conference do |f|  f.name 'NFC'  f.association :leagueendFactory.define :division do |f|  f.name 'north'  f.association :conferenceendFactory.define :team do |f|  f.name 'Packers'  f.locale 'Green Bay'  f.association :divisionendFactoryGirl.define do  factory :event do    association :league    association :home_team,:factory => :team    association :away_team,:factory => :team  endend

那么,有了这些,我将如何为same_league验证方法编写规范?

describe Event do  pending 'should not allow home_team and away_team to be from two different leagues'end

我的问题是了解在不同联盟中创建两个团队并将其中一个与home_team相关联,另一个与event_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 => @second_league.ID)    event = Factory(:event,:away_team_ID => away_team.ID)    event.valID?.should == false  endend
总结

以上是内存溢出为你收集整理的ruby-on-rails – Rails / Rspec – 编写涉及自定义验证和belongs_to关联的规范全部内容,希望文章能够帮你解决ruby-on-rails – Rails / Rspec – 编写涉及自定义验证和belongs_to关联的规范所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1274217.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存