This article will show how to “test drive” the prime factors kata in Elixir with ESpec, a spec style unit testing framework.
For an explanation of TDD itself, see this article.
Problem: We want to factor a number into it’s base primes. For example 9 can be factored into 3x3 and 20 can be factored into 2x2x5.
The first stage in TDD is red where we create a failing test. It’s important to remember that we don’t want to write any production code until that’s the only way we can make a test pass.
First test: factor 2
For our first test, we’ll attempt to factor 2, which should result in an array containing only two.
defmodule PrimeFactorsSpec do
use ESpec
example "2" do
PrimeFactors.factor(2)
|> to(be([2]))
end
end
Initially, this won’t even compile so it isn’t failing for the right reason.
(UndefinedFunctionError) function PrimeFactors.factor/1 is undefined or private
We write enough code to allow it to compile and run.
defmodule PrimeFactors do
def factor(number) do
[]
end
end
We verify that the test is still failing, now for the right reason.
Expected `[]` to equal (==) `[2]`, but it doesn't.
Next we move to green, where we need to make the test pass. We’re not looking to make the code beautiful or performant or reusable at this point. We’re looking to make the test pass in the easiest possible way.
defmodule PrimeFactors do
def factor(number) do
[2]
end
end
We know that hard coding the 2 at this point is silly and that it’s going to cause problems later but we don’t care. The TDD process will get us there at the right time. For now, we only care about the one case that we’ve written a test for.
Now we come to the third stage in the process, refactor. We look at the code and the tests and we look to see if there’s anything we might want to improve. There usually isn’t for the first test but there certainly will be things to improve once we have a couple of tests and so we always want to consider this.
Check it in. It’s certainly not complete but what we do have is a tiny slice of working, tested, code.
Second test: factor 3
We already recognized that hard coding the 2 was bad so let’s create another test that forces us to fix that. We’re back in red
We’re adding a second test here, not replacing the first. We are building up a suite of these tests.
example "3" do
PrimeFactors.factor(3)
|> to(be([3]))
end
We run the test and it fails for the right reason.
Expected `[2]` to equal (==) `[3]`, but it doesn't.
expected: [3]
actual: [2]
We satisfied red and now move on to green. Change the production code to make the test pass. The simplest thing that could work.
defmodule PrimeFactors do
def factor(number) do
[number]
end
end
Now both tests are passing so we consider the refactor step. Is there any duplication? Anything we might want to improve at this point? I’m thinking no, so we’ll move on.
Check it in.
Third test: factor 4 (two times a prime)
red: The test for 4 is straight forward. We should get back two and two.
example "4" do
PrimeFactors.factor(4)
|> to(be([2,2]))
end
green: The implementation is more complex here because for the first time, we have a chance to actually calculate something instead of just hard coding.
I notice that any even number can be divided by 2 so we can add another function head that matches just on even numbers and returns two and whatever is left by number divided by two.
defmodule PrimeFactors do
def factor(number) when rem(number, 2) == 0 do
[2, div(number, 2)]
end
def factor(number) do
[number]
end
end
When the tests are run again, we discover that while the test for 4 (the immediate concern) is passing, one of our earlier tests is now failing. Specifically the test for 2 which is now returning [2, 1]
We’re still in the green phase so we want the simplest solution that gets us working again. We’ll add a special case for 2.
defmodule PrimeFactors do
def factor(2) do
[2]
end
def factor(number) when rem(number, 2) == 0 do
[2, div(number, 2)]
end
def factor(number) do
[number]
end
end
All tests are passing so we move on to refactor. I’m really not liking all the hard coded 2’s but I’m not sure how I want to handle that yet so I’ll defer fixing it. It’s likely now that we’ll work for two times any prime but we may not work for powers of two times a prime. Let’s test-drive that.
Check it in.
Fourth test: factor 8 (power of two times a prime)
red: Create a test for 8 and watch it fail.
example "powers of two times a prime" do
PrimeFactors.factor(8)
|> to(be([2, 2, 2]))
end
green: Let’s add a bit of recursion in the function head that handles even numbers.
defmodule PrimeFactors do
def factor(2) do
[2]
end
def factor(number) when rem(number, 2) == 0 do
[2 | factor(div(number, 2))]
end
def factor(number) do
[number]
end
end
Now it looks like we’ve handled all powers of two times a prime.
refactor: Back to the refactor step, and I’m increasingly unhappy with all the hard coded 2’s so let’s deal with that now.
defmodule PrimeFactors do
def factor(number) do
factor(number, 2)
end
def factor(number, divisor) when number == divisor do
[number]
end
def factor(number, divisor) when rem(number, divisor) == 0 do
[divisor | factor(div(number, divisor))]
end
def factor(number, _divisor) do
[number]
end
end
All the original methods have now been converted to a factor/2 that takes a divisor. The original factor/1 now passes in the divisor as 2. So 2 is still hard coded but it’s only in one place now, which makes the code feel much cleaner to me.
All tests continue to pass so we move on.
Check it in.
Fifth test: factor 9 (power of three times a prime)
red: We know that powers of two are all working and it feels pretty obvious that it’s going to break when we attempt multiple of 3 so let’s start there. Next test is for 3x3
example "3 times a prime" do
PrimeFactors.factor(9)
|> to(be([3, 3]))
end
Test fails, and for the right reason.
expected: [3, 3]
actual: [9]
green: For the case of 9, we’ll fall through to the last factor
function. What if we use some recursion there to try the next number up?
defmodule PrimeFactors do
def factor(number) do
factor(number, 2)
end
def factor(number, divisor) when number == divisor do
[number]
end
def factor(number, divisor) when rem(number, divisor) == 0 do
[divisor | factor(div(number, divisor))]
end
def factor(number, divisor) do
factor(number, divisor + 1)
end
end
All tests continue to pass.
refactor: The code and the tests are both looking pretty clean so nothing I want to change. We still always need to stop and reflect at this point though.
At this point, I think we’ve handled every possible case. We might want to spot-check some larger numbers to see if we can uncover something that we didn’t handle, but that’s more exploratory testing and not test-driven development so we’ll stop here.
Check it in.
Recap
We took one step at a time to solve the problem. We created one tiny test and watched it fail (red), we did the simplest thing to make it pass (green), and we looked for opportunities to make it better (refactor). Then we did it again, and again, until we’d finished the feature.