Merge pull request #7412 from andrewpbrett/no-zero-unit-values

Add greater-than-zero validation to variant unit_value
This commit is contained in:
Andy Brett
2021-04-15 10:05:38 -07:00
committed by GitHub
5 changed files with 19 additions and 2 deletions

View File

@@ -59,6 +59,8 @@ module Spree
%w(weight volume).include?(variant.product.andand.variant_unit)
}
validates :unit_value, numericality: { greater_than: 0 }
validates :unit_description, presence: true, if: ->(variant) {
variant.product.andand.variant_unit.present? && variant.unit_value.nil?
}

View File

@@ -0,0 +1,10 @@
class AddUnitValueConstraint < ActiveRecord::Migration[5.0]
def up
execute "UPDATE spree_variants SET unit_value = 1 WHERE unit_value <= 0"
execute "ALTER TABLE spree_variants ADD CONSTRAINT positive_unit_value CHECK (unit_value > 0)"
end
def down
execute "ALTER TABLE spree_variants DROP CONSTRAINT positive_unit_value"
end
end

View File

@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20210326094519) do
ActiveRecord::Schema.define(version: 20210414171109) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

View File

@@ -130,7 +130,7 @@ describe Api::V0::VariantsController, type: :controller do
it "can create a new variant" do
original_number_of_variants = variant.product.variants.count
api_post :create, variant: { sku: "12345", unit_value: "weight", unit_description: "L" }, product_id: variant.product.to_param
api_post :create, variant: { sku: "12345", unit_value: "1", unit_description: "L" }, product_id: variant.product.to_param
expect(attributes.all?{ |attr| json_response.include? attr.to_s }).to eq(true)
expect(response.status).to eq(201)

View File

@@ -18,6 +18,11 @@ module Spree
variant.price = 0
expect(variant).to be_valid
end
it "should validate unit_value is greater than 0" do
variant.unit_value = 0
expect(variant).to be_invalid
end
end
context "price parsing" do