Rails / Rspec - a specification record that includes custom validation and association

I have the following AR has_many, belongs_to relationships:

League → Conference → Division → Team

I have an Event model that looks like this:

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 

And some plants:

 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 

So how to do this, how can I write a specification for the same league check method?

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

My problem is to know that the easiest way to create two teams in different leagues and associate them with home_team and the other with away_team in the event model.

+4
source share
1 answer

You can store instances that you create in factories, and then explicitly use your ID to populate foreign keys for subsequent factories.

Here I create two leagues and then set up two tests. Where in a tournament there are two teams in one league and the other with two teams in different leagues. This way I can check if the event object is being checked correctly:

 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 
+3
source

Source: https://habr.com/ru/post/1394535/


All Articles