I have a model eclub, which has many invites, and I want to limit the number of invites that can be added. My model looks like this
class Eclub < ActiveRecord::Base
has_many :invites, dependent: :destroy
validates :invites, length: {maximum: 50, message: 'The maximum number of invites have been sent' }
which according to this SO answer should work provided I am not concerned about invites marked for destruction. My rspec test first creates an eclub and successfully adds 50 invites to it. Then
invite = Invite.new(name: 'Too Many', email: 'extra@gmail.com')
eclub.invites << invite
expect(eclub).to be_invalid
expect(eclub.errors[:invites].first).to include 'maximum number'
expect(eclub.reload.invites.size).to eq 50
The first two expectations pass, but the last fails with
Failure/Error: expect(eclub.reload.invites.size).to eq 50
expected: 50
got: 51
How do I prevent the extra invite from being added to the collection?