Search code examples
associationsrspec-rails

Rails / Rspec - writing spec for class name of belongs_to association


Given the code below:

(1) How would you write a spec to test that the class name of home_team and away_team should be a Team class?

(2) Should you even bother to write such a spec? I'm not sure I see the value in doing so, but 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

Would be nice if shoulda had something like:

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

Solution

  • Here is a blog post about why this really shouldn't be done:

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

    To summarize, associations are the structure of your application. RSpec is meant to test behaviors. So, its probably better if you write tests for the behavior that is derived from the home_team or the away_team.

    Take for example if you wanted the name of the home_team. It would be better if you wrote a method like this:

    def home_team_name
      home_team.name
    end
    

    This is a behavior that the event class would ask the home_team for. You could write a spec such as:

    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 
    

    This would be a great example of testing the behavior of the association, without directly testing the structure of your application.

    Also, as a point, Rails expects that home_team is of class 'Team', and there is no need to test the framework, it is well tested and documented. The only way that I could see doing this would be on a temporary basis, if you needed to improve your understanding of the way that assocaitions work.