0
0
Rubyprogramming~10 mins

Test-driven development workflow in Ruby

Choose your learning style9 modes available
Introduction

Test-driven development helps you write code that works right from the start. It makes sure your program does what you want by testing it first.

When you want to build a small feature and be sure it works before adding more.
When fixing bugs to make sure the problem is solved and does not come back.
When learning a new programming concept and want to check your understanding.
When working in a team to keep code reliable and avoid breaking others' work.
When improving old code safely by testing changes step-by-step.
Syntax
Ruby
# 1. Write a test that fails
# 2. Write just enough code to pass the test
# 3. Run tests and see them pass
# 4. Refactor code to improve it
# 5. Repeat for next feature or fix

The test is written before the actual code.

Tests guide the coding process and catch mistakes early.

Examples
This is a simple test that checks if 2 + 3 equals 5.
Ruby
require 'minitest/autorun'

class TestCalculator < Minitest::Test
  def test_addition
    assert_equal 5, 2 + 3
  end
end
This is the code written to pass the test above.
Ruby
class Calculator
  def add(a, b)
    a + b
  end
end
Test updated to use the Calculator class method.
Ruby
require 'minitest/autorun'

class TestCalculator < Minitest::Test
  def test_addition
    calc = Calculator.new
    assert_equal 5, calc.add(2, 3)
  end
end
Sample Program

This program shows the full test-driven workflow: first the test checks addition, then the Calculator class is created with the add method to pass the test.

Ruby
require 'minitest/autorun'

class Calculator
  def add(a, b)
    a + b
  end
end

class TestCalculator < Minitest::Test
  def test_addition
    calc = Calculator.new
    assert_equal 5, calc.add(2, 3)
  end
end
OutputSuccess
Important Notes

Always start by writing a test that fails to know what you want your code to do.

Keep tests small and focused on one thing at a time.

Refactor your code after tests pass to keep it clean and simple.

Summary

Write tests before code to guide development.

Run tests often to catch errors early.

Refactor code safely with tests as a safety net.