Test Driven Development | Explained with Examples and Tools
This blog talks about test driven development as well as its importance. Moreover, it also elaborates test driven development with examples.
What is test driven development (TDD) ?
Test driven development is the process of writing tests before writing the actual code. It is a method in software development in which you first write a test and it fails, then write the code to pass the test, and then clean up the code. This method ensures that the code is always tested and reduces bugs, improving code quality and correctness.
Test driven development examples
Let's consider an ecommerce application feature - adding an item to a shopping cart for test driven development.
Step 1: Write a Failing Test
Test: Adding an Item to the Cart (Using Rspecs)
# spec/cart_spec.rb
require 'cart'
RSpec.describe Cart do
it 'adds an item to the cart' do
cart = Cart.new
item = { id: 1, name: 'Laptop', price: 1000 }
cart.add_item(item)
expect(cart.items).to include(item)
end
end
Step 2: Write the Minimum Code to Pass the Test
Sample cart class
# lib/cart.rb
class Cart
attr_reader :items
def initialize
@items = []
end
def add_item(item)
@items << item
end
end
Step 4: Extend the Test
Next we move on to writing additional tests to handle more complex cases like calculating the total price of the items in the cart.
Sample Test: Calculating Total Price
RSpec.describe Cart do
it 'calculates the total price of items in the cart' do
cart = Cart.new
item1 = { id: 1, name: 'Laptop', price: 1000 }
item2 = { id: 2, name: 'Mouse', price: 50 }
cart.add_item(item1)
cart.add_item(item2)
expect(cart.total_price).to eq(1050)
end
end