Rails / Rspec - specification record for class name association_to

Based on the code below:

(1) How do you write a specification to verify that the class name home_team and away_team should be the class Team?

(2) Do you even have to write such a specification? I’m not sure I see the value in this, but I wanted to get your thoughts.

class Event < ActiveRecord::Base

  belongs_to :home_team, :class_name => 'Team', :foreign_key => :home_team_id
  belongs_to :away_team, :class_name => 'Team', :foreign_key => :away_team_id

end

describe Event do

  it { should belong_to(:home_team) }
  it { should belong_to(:away_team) }

end

It would be nice if we had something like:

it { should belong_to(:home_team).with_class_name(:team) }
+5
source share
2 answers

Here's a blog post about why this should not be done:

http://blog.davidchelimsky.net/2012/02/12/validations-are-behavior-associations-are-structure/

, . RSpec . , , , , home_team away_team.

, , home_team. , :

def home_team_name
  home_team.name
end

, home_team . , :

describe '#home_team_name' do
  before do
    @home_team = Team.new(:name => 'The Home Team')
    @event = Event.new(home_team_id: @home_team.id)
  end

  it 'should return the name of the home team' do
    @event.home_team_name.should == 'The Home Team'
  end
end 

.

, Rails , home_team "Team", , . , , - , , .

+5

-, - ...

it { should belong_to(:home_team).class_name(:team) }

it { should belong_to(:home_team).class_name('Team') }
+3

All Articles