Rails嵌套模型创建不遵守验证约束

时间:2012-11-05 05:20:18

标签: ruby-on-rails ruby-on-rails-3 validation rspec

我有一个Customer模型,其中包含多个地址对象,如下所示:

客户模式:

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 个答案:

答案 0 :(得分:1)

啊,我终于搞清楚了!我需要在上一个规范中将create更改为create!,以便使失败的验证实际上出错。