我的模特关系喜欢
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
这是轨道问题吗?
如何解决测试用例?