[rspec-users] Validations based on associations

Pat Maddox pergesu at gmail.com
Mon Jan 1 03:47:53 EST 2007

My model is very simple, it's mostly just a join table that represents
which tournaments a user has registered for.

class Registration < ActiveRecord::Base
  belongs_to :user
  belongs_to :tournament

  validates_presence_of :user_id, :tournament_id
  validates_uniqueness_of :user_id, :scope => :tournament_id

the validates_uniqueness checks to make sure there's no record that
has the same user_id and tournament_id.

Is there a relatively easy way to specify this behavior?  The only way
that I know is to do something like

context "A Registration with a User and Tournament" do
  setup do
    @user = User.new
    @user.save false
    @tournament = Tournament.new
    @tournament.save false
    @reg = Registration.new(:user => @user, :tournament => @tournament)

  specify "should be valid" do

  specify "should not be valid if a registration with the same details
already exists" do
    Registration.new(:user => @user, :tournament =>

Well actually that's obviously pretty easy :)  Is it bad that I'm tied
to the implementations of User and Tournament at all?  ActiveRecord
dictates that, so I guess it's not a problem to have that in my spec
at all.

Anyway this is just the spec I came up with and I'm wondering if
anyone else has a better idea.


More information about the rspec-users mailing list