Red Green Repeat Adventures of a Spec Driven Junkie

Test First, not Tests First

The main tenet of Test Driven Development is:

Write a failing test before writing the code.

Simple - test first. Code second.

Doing TDD

If a person wrote the following in the test file:

it 'function_a returns 1' do
  expect(function_a(1)).to eq(1)
end

it 'function_b returns 2' do
  expect(function_b(2)).to eq(2)
end

it 'function_c returns 3' do
  expect(function_c(3)).to eq(3)
end

and then wrote the following in the code file:

def function_a(input)
  return input
end

def function_b(input)
  return input
end

def function_c(input)
  return input
end

Would they be practicing test driven development?

If yes, why? If not, why?

TDD Trap

The above sequence does align with the tenet of Test Driven Development by having all the tests first for functions function_a, function_b, function_c, then writing the implementation for each function.

Where’s the trap?

The above sequence first implements the three tests and then implements three solutions at once.

The key idea is to implement one test, then one solution. No more, no less.

TDD Flow

The sequence to implement the above would really be the following:

First, test function_a:

it 'function_a returns 1' do
  expect(function_a(1)).to eq(1)
end

When the test fail, implement solution:

def function_a(input)
  return input
end

then, the next test in the test file would be:

it 'function_a returns 1' do
  expect(function_a(1)).to eq(1)
end

it 'function_b returns 2' do
  expect(function_b(2)).to eq(2)
end

Run tests, see failure and the solution in the code file would be:

def function_a(input)
  return input
end

def function_b(input)
  return input
end

Repeat again for test and code function_c.

Key Idea

Only write one test, validate failure, then solve. Writing multiple tests, then solving is better than coding first. Writing multiple tests and getting them all to pass at once only makes your job harder.

Make one test, when it fails, write the code to make the test pass.

It’s test first, not: tests first.

:-)