Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Created June 5, 2025 19:52
Show Gist options
  • Select an option

  • Save chrisbloom7/98a1980a80baa05dcf25130a21d833af to your computer and use it in GitHub Desktop.

Select an option

Save chrisbloom7/98a1980a80baa05dcf25130a21d833af to your computer and use it in GitHub Desktop.
Example of a refactored discount_calculator.rb logic into a reusable class using a hash lookup for cleaner, more scalable code, with safeguards and test coverage in both RSpec and Minitest.
require "bundler/inline"
gemfile do
gem "rspec"
gem "minitest"
end
class DiscountCalculator
DISCOUNTS = {
'SUMMER10' => 0.10,
'WELCOME5' => 0.05,
'SUPER20' => 0.20
}.freeze
def self.calculate(price, code)
return 0 unless price.is_a?(Numeric) && price >= 0
discount_rate = DISCOUNTS[code] || 0
discounted_price = price - (price * discount_rate)
[discounted_price, 0].max
end
end
# ------------------------------------------
# RSpec Tests (if using rspec)
# Run: rspec discount_calculator.rb
# ------------------------------------------
if defined?(RSpec)
RSpec.describe DiscountCalculator do
describe '.calculate' do
it 'applies SUMMER10 correctly' do
expect(described_class.calculate(100, 'SUMMER10')).to eq(90)
end
it 'applies WELCOME5 correctly' do
expect(described_class.calculate(100, 'WELCOME5')).to eq(95)
end
it 'applies SUPER20 correctly' do
expect(described_class.calculate(100, 'SUPER20')).to eq(80)
end
it 'returns original price if code is unknown' do
expect(described_class.calculate(100, 'UNKNOWN')).to eq(100)
end
it 'caps final price at 0' do
expect(described_class.calculate(100, 'SUPER20')).to be >= 0
expect(described_class.calculate(-100, 'SUPER20')).to eq(0)
end
end
end
end
# ------------------------------------------
# Minitest Tests (if using minitest)
# Run: ruby discount_calculator.rb
# ------------------------------------------
if __FILE__ == $0
require 'minitest/autorun'
class DiscountCalculatorTest < Minitest::Test
def test_summer10
assert_equal 90, DiscountCalculator.calculate(100, 'SUMMER10')
end
def test_welcome5
assert_equal 95, DiscountCalculator.calculate(100, 'WELCOME5')
end
def test_super20
assert_equal 80, DiscountCalculator.calculate(100, 'SUPER20')
end
def test_unknown_code
assert_equal 100, DiscountCalculator.calculate(100, 'INVALID')
end
def test_negative_price_returns_zero
assert_equal 0, DiscountCalculator.calculate(-100, 'SUMMER10')
end
def test_nil_code
assert_equal 100, DiscountCalculator.calculate(100, nil)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment