Practicing Advanced TDD with Ruby through ShoppingCart Enhancements

Introduction to the Shopping Cart Module

Welcome to your fifth and final unit of this course, dedicated to practicing Test-Driven Development (TDD) utilizing Ruby and RSpec. We're going to finish building our ShoppingCart system by adding even more features to our class.

In this course, emphasis is placed on hands-on practice, where you'll receive requirements through tests, one at a time. Your task is to write tests AND implement code that makes each test pass, simulating a real-world TDD environment. Previously, I wrote the tests for you; this time, it's all up to you!

Remember to use the core concepts of the Red-Green-Refactor cycle while completing these coding exercises. I'm still here to help! Just ask.

Final Requirements for `ShoppingCart` Class

In this section, you'll learn how to implement the following features:

  1. Enforcing a Quantity Limit for a Single Item
  2. Retrieving Item Details by ID
  3. Applying and Validating Discount Codes
  4. Handling the Addition of Existing Items and Ensuring Quantity Limits

11. Quantity Limit for a Single Item

  • Description: The cart should enforce a maximum quantity limit of 10 for a single type of item, preventing more than the allowed amount from being added.
  • Details
    • Utilize the add_item(item, quantity) method to add items to the cart.
    • Ensure an exception is raised when adding a quantity that exceeds a limit of 10 for a single item.
    • The exception message should clearly state, "Maximum quantity exceeded" when the limit is breached.
  • Examples: Attempting to add 11 units of Product.new('1', 'Book', 10) should raise an exception indicating "Maximum quantity exceeded."
Ruby
class ShoppingCart
  attr_reader :items

  def initialize
    @items = []
  end

  def add_item(item, quantity = 1)
    existing_item = @items.find { |i| i[:id] == item[:id] }
    new_quantity = existing_item ? existing_item[:quantity] + quantity : quantity
    raise "Maximum quantity exceeded" if new_quantity > 10

    if existing_item
      existing_item[:quantity] = new_quantity
    else
      @items << item.merge(quantity: quantity)
    end
  end
end

# Example Usage
cart = ShoppingCart.new
begin
  cart.add_item({ id: '1', name: 'Book', price: 10 }, 11)
rescue => e
  puts e.message # Output: "Maximum quantity exceeded"
end
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal