2

我的模特关系喜欢

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

工厂.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  

这是轨道问题吗?

如何解决测试用例?

4

1 回答 1

0

仅针对数据库的唯一性验证检查。在您的情况下,您有两个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.

于 2012-12-13T13:41:38.673 回答