From 8fbeea986d06a0052ce0132717f22b6ff8bd1a04 Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Fri, 14 Apr 2023 20:49:46 -0600 Subject: AƱade validador de existencias a ProductCart MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/product_cart.rb | 7 +++++++ spec/factories/product_cart.rb | 2 +- spec/models/product_cart_spec.rb | 10 ++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/models/product_cart.rb b/app/models/product_cart.rb index 09e7a25..d4232cb 100644 --- a/app/models/product_cart.rb +++ b/app/models/product_cart.rb @@ -8,10 +8,17 @@ class ProductCart < ApplicationRecord validates :quantity, presence: true, comparison: { greater_than: 0 } validate :sole_product_in_cart + validate :product_quantity def sole_product_in_cart return if cart.nil? || cart.products.find_by(id: product_id).nil? errors.add(:product_id, "cart already has product with id #{product_id}") end + + def product_quantity + return if product.nil? || product.available_quantity > quantity + + errors.add(:product_id, 'not enough in existence') + end end diff --git a/spec/factories/product_cart.rb b/spec/factories/product_cart.rb index 713fd0a..95094dd 100644 --- a/spec/factories/product_cart.rb +++ b/spec/factories/product_cart.rb @@ -3,7 +3,7 @@ FactoryBot.define do factory :product_cart, class: 'ProductCart' do cart { create(:cart) } - product { create(:product) } + product { create(:product, available_quantity: 2000) } quantity { rand(1..1000) } end end diff --git a/spec/models/product_cart_spec.rb b/spec/models/product_cart_spec.rb index 2c4d9d1..46860d3 100644 --- a/spec/models/product_cart_spec.rb +++ b/spec/models/product_cart_spec.rb @@ -20,4 +20,14 @@ RSpec.describe ProductCart, type: :model do expect(another_product_cart.errors[:product_id]).to be_present end end + + describe '#product_quantity' do + it "validates the requested quantity against the product's available quantity" do + product = create(:product, available_quantity: 5) + another_product_cart = build(:product_cart, cart: product_cart.cart, product:, quantity: 10) + + expect(another_product_cart.save).to be_falsey + expect(another_product_cart.errors[:product_id][0]).to eq('not enough in existence') + end + end end -- cgit v1.2.3