Test Driven Development (TDD)

Now that I actually have some tools to practice TDD, I find it much easier to write and debug a program!

When I was teaching myself javascript and ruby, I would write programs, and in the process, I would frequently want to check if it was working up to a certain point. My solution at the time (before I knew anything about TDD), would involve adding a couple lines of code to print the values of variables to the console, so I could see if they were what I expected. For example, I wrote a program to determine if a number is prime or not, called primes.rb, with a method called isPrime?, and frequently wanted to test some base cases, so I would insert something like:

puts isPrime?(1)
puts isPrime?(2)
puts isPrime?(3)
puts isPrime?(4)
puts isPrime?(42000)
puts isPrime?(97379)

into my code. I would then run the script and hope for:

This was quite a pain because every time I changed the program, I would have to run it again to see if it still worked (assuming it was working before).
In a sense, I was doing test driven development, but in a very crude and amateur way.

So what is Test Driven Development for real?
Using rspec and guard-rspec, which are ruby gems, you can write your own test to check you code as you write it. Using the example above, I could write a primes_spec.rb file (by convention, spec files are placed in a spec/lib/ directory, and should match the lib/ directory at your project root)

If you are running guard in your terminal (I’ll assume you know how to install gems, and figure out how to run guard), whenever you make a change to your primes.rb code, guard will automatically run those tests and give you a pass or fail status.

Now, there is more to TDD than just writing code and writing tests for it. There is a methodology to the process, called ‘Red, Green, Refactor’ which I will discuss in the next blog post.


About Aaron Glasenapp

I am a freelance Web/Rails developer and a hard core recreational mathematician.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: