I have a Customer model that has_many polymorphic Address objects, like so:
Customer Model:
class Customer < ActiveRecord::Base
has_many :mailing_addresses, :as => :addressable, :class_name => 'Address', dependent => :destroy
accepts_nested_attributes_for :mailing_addresses
validates :mailing_addresses, :presence => true
validates_associated :mailing_addresses
end
Address Model:
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
validate :validate_quota
private
def validate_quota
case addressable_type
when "Customer"
customer = Customer.find(addressable_id)
if customer.mailing_addresses.size >= 3
puts "Adding too many records"
errors.add(:addressable, "Too many records")
end
end
end
I am also using RSpec to test that the quota constraint is respected. So this spec passes, for example:
it "observes quota limit" do
customer = FactoryGirl.create(:customer, :number_of_mailing_addresses => 3)
expect {
address = FactoryGirl.create(:mailing_address, :addressable => customer)
}.to raise_error
customer.mailing_addresses.count.should eq(3)
end
Which is good. However, this fails horribly:
it "fails add if already 3 addresses" do
customer = FactoryGirl.create(:customer, :number_of_mailing_addresses => 3)
expect {
customer.mailing_addresses.create( FactoryGirl.attributes_for(:mailing_address).except(:addressable) )
}.to raise_error
end
I can even see in the spec output that the Address validation is failing, but for some reason it doesn’t raise an error in “customer.mailing_addresses.create()”, nor does that failed validation prevent the 4th Address model from saving to the database.
What am I missing?
Ah, I finally figured it out! I needed to change
createtocreate!in my last spec in order to make the failing validation actually throw an error.