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)
endand 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
endWould 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)
endWhen the test fail, implement solution:
def function_a(input)
return input
endthen, 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)
endRun 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
endRepeat 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.
:-)