Test Driven Development (TDD) is a programming approach that flips the usual coding process on its head. Instead of writing your code first and testing it later, you start by writing tests for your code before you even create it.
Here's how it works:
TDD might seem counterintuitive at first, but it can lead to more reliable and maintainable code. Give it a try in your next project.
Write the test first: Before coding, write a test that defines the expected behavior.
Example: You're building a calculator app. Write a test for addition:
def test_addition
assert_equal 5, Calculator.add(2, 3)
end
Run the test (it should fail): Run the test before writing any code. It should fail because the functionality doesn't exist yet.
Example: Running the test shows a failure because the Calculator class and add method don't exist.
Write the minimum code to pass the test: Implement just enough code to make the test pass.
Example: Create the Calculator class with an add method:
class Calculator
def self.add(a, b)
a + b
end
end
Run the test again (it should pass): The test should now pass with the implemented code.
Example: Running the test shows a success because the add method works correctly.
Refactor if necessary: Improve the code while ensuring the test still passes.
Example: No refactoring needed for this simple case, but you might optimize for larger numbers later.
Repeat for new features: Continue this cycle for each new feature or functionality.
Example: Next, write a test for subtraction, then implement it, and so on.