Skip to content

Commit

Permalink
Don't crash on price set to 0
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaszreszke committed Aug 6, 2024
1 parent 15db137 commit fd218e1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
23 changes: 23 additions & 0 deletions rails_application/app/controllers/products_controller.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
class ProductsController < ApplicationController
class CreateProduct
attr_reader :price, :vat_rate, :product_id, :name

def initialize(price:, vat_rate:, product_id:, name:)
@price = price
@vat_rate = vat_rate
@product_id = product_id
@name = name
end

def valid?
price.present? && vat_rate.present? && product_id.present? && name.present? && price.to_d > 0 && vat_rate.to_d > 0
end
end

def index
@products = Products::Product.all
end
Expand All @@ -16,6 +31,10 @@ def edit
end

def create
is_form_valid = CreateProduct.new(**product_params).valid?

return head :bad_request unless is_form_valid

ActiveRecord::Base.transaction do
create_product(params[:product_id], params[:name])
if params[:price].present?
Expand Down Expand Up @@ -101,4 +120,8 @@ def set_product_future_price_cmd(product_id, price, valid_since)
valid_since: valid_since
)
end

def product_params
params.permit(:name, :price, :vat_rate, :product_id).to_h.symbolize_keys.slice(:price, :vat_rate, :product_id, :name)
end
end
18 changes: 18 additions & 0 deletions rails_application/test/integration/products_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,22 @@ def test_happy_path
unit: ""
)
end

def test_does_not_crash_when_setting_products_price_to_0
register_customer("Arkency")
product_id = SecureRandom.uuid

get "/products/new"
assert_select "h1", "New Product"
post "/products",
params: {
"authenticity_token" => "[FILTERED]",
"product_id" => product_id,
"name" => "product name",
"price": "0",
"vat_rate" => "10"
}

assert_response :bad_request
end
end

0 comments on commit fd218e1

Please sign in to comment.