Mongoid saves documents despite invalid user checks

I'm not sure if this is a problem with Mongoid or with the standard Rails validators, but invalid documents are still stored in the database.

I have models configured for something like:

class League
  include Mongoid::Document

  has_many :teams

  validate do
    if teams.size > 12
      errors.add(:teams, 'too many teams')
    end
  end
end

class Team
  include Mongoid::Document

  belongs_to :league
end

I would expect the next test to pass, but that is not the case. Instead of my special check to prevent the addition of more than 12 teams to the League, the league receives salvation from 13 teams anyway.

# Factory for a League.
FactoryGirl.define do
  factory :league do
  name "Test League"

  factory :league_with_teams do
    ignore do
      teams_count 5
    end

    after(:create) do |league, evaluator|
      FactoryGirl.create_list(:team, 
                              evaluator.teams_count, 
                              league: league)
    end
  end
end

describe League do
  it "should not allow more than 12 teams" do
    league = FactoryGirl.create(:league_with_teams, teams_count: 12)
    league.teams << FactoryGirl.create(:team)
    league.should_not be_valid # passes
    League.find(league.id).teams.size.should eq(12) # fails
  end
end

The funny thing is, if I change the line in the test, which adds the 13th command to use the assembly instead of create league.teams << FactoryGirl.build(:team), then the test will pass. However, this is not a solution, because I want to guarantee that there can be no more than 12 teams in the League, regardless of whether the added teams are new or already in the database.

, ?

Edit

Team, , .

class Team
  include Mongoid::Document

  belongs_to :league

  validate do |team|
    if league.teams.size > 12
      errors.add :base, "cannot have more than 12 teams in a league"
    end
  end
end

, , << push , . , , , ? , ?

+5
1

, << push, .

:

league.teams << FactoryGirl.create(:team, league: league)

0

All Articles