使用accepts_nested_attributes_for进行rails-rspec唯一性验证

时间:2012-12-13 13:27:46

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

我的模型关系

class Cart < ActiveRecord::Base
  has_many :cart_items, :inverse_of => :cart, :dependent => :destroy
  accepts_nested_attributes_for :cart_items, :allow_destroy => :true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
  validates_associated :cart_items
  validates :cart_name, :presence => {:message => "Must be filled" }
end

class CartItem < ActiveRecord::Base
  belongs_to :cart, :inverse_of => :cart_items
  validates :cart_item_no, :presence => {:message => "Must be filled"}, :uniqueness => {:message => "Already exists" }
end

factories.rb

FactoryGirl.define do
  factory :cart do
    cart_name "sample"
    factory :cart_with_cart_items do
      after(:build) {|cart|
        2.times { cart.cart_items.build(attributes_for(:cart_item)) }
      }
      after(:create) {|cart|
        cart.cart_items.each {|cart_item| cart_item.save! }
      }
    end
  end

  factory :cart_item  do
    cart_item_no 1
    cart
  end
end

以下测试用例总是失败

it "should not be valid with same cart_id" do
  cart = FactoryGirl.build(:cart_with_cart_items)
  cart.should_not be_valid
end

然后我在控制台中进行探索,验证总是通过以下代码的示例在 cart_items 中使用相同的* cart_item_no *两次返回true。

cart = Cart.new(:cart_name => "yyy")
  => #<Cart id: nil, cart_name: "yyy">
2.times { cart.cart_items.build(:cart_item_no => 1000) }
  => 2
cart.cart_items 
  => [#<CartItem id: nil, cart_item_no: 1000>, #<CartItem id: nil, cart_item_no: 1000>]
cart.valid?
  => true
cart.save!
  => true  

这是导轨问题吗?

如何解决测试用例?

1 个答案:

答案 0 :(得分:0)

Uniqness验证仅针对数据库进行检查。在您的情况下,您有两个cart_items相互冲突但不与数据库中的任何记录冲突,因此单独两者都有效,这就是您的验证通过的原因。

您可以在Cart课程中添加自定义验证(未经测试):

validates :unique_cart_items

def unique_cart_items
  unless cart_items.collect(&:cart_item_no).uniq.size < cart_items.size
    # set some error attribute here
  end
end

这会将唯一cart_item_no值的数量与cart_items的数量进行比较。如果它们不相同,则会出现重复的cart_item_no