0

我有一个具有多个多态地址对象的客户模型,如下所示:

客户型号:

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

地址型号:

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

我还使用 RSpec 来测试配额约束是否得到遵守。所以这个规范通过了,例如:

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

哪个好。但是,这非常失败:

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

我什至可以在规范输出中看到地址验证失败,但由于某种原因,它不会在“customer.mailing_addresses.create()”中引发错误,验证失败也不会阻止第四地址模型保存到数据库。

我错过了什么?

4

1 回答 1

1

啊,我终于想通了!为了使失败的验证实际上引发错误,我需要更改create为我的上一个规范。create!

于 2012-11-05T06:54:25.783 回答