Setting up a Rakefile for TDD

This year I attended RubyConf India which was extremely awesome to say the least. I interacted with great programmers and got to learn many new techniques to get most out of this spectacular programming language.

One of my favourite takeaway from Conference was Test Driven Development (TDD), which was showcased by Jim Weirich, creator of Rake. You can take a look at the keynote in this video.

If you notice, Jim mentions that he had setup Rakefile beforehand in interest of time. Allow me to show you how to do it yourself.

Note: I am showing how to setup a Rakefile for test/unit and not for rspec. I’ll cover that someday later.

Open your terminal and cd to the directory where you want to keep your Rakefile. Now, run

$ touch Rakefile

and open the file created. touch creates an empty file for us. Let’s fill it up.

First thing our rake file needs to do is add current directory to ruby’s path so we can use require in place of require_relative.

$: << File.dirname(File.absolute_path(__FILE__))

The $: is global variable in ruby for path directories. So, this line basically adds the directory of current file to path. Of course, this is valid only while the program is running and is not a permanent change.

Next, we need to add test tasks so we can run the command rake test and it automatically runs all the tests for us.

require 'rake/testtask'

Rake::TestTask.new(:test) do |t|
  t.libs << "."
  t.test_files = FileList["test/test*.rb"]
  t.verbose = true
end

This makes available the rake test command. One thing you should understand is that our rake test command will look for tests in the test folder. Also, the name of our tests files should start with the word test and end with .rb. We let rake know all these by t.test_files = FileList["test/test*.rb"] statement.

Try running rake at this point. You’ll probably get something like

rake aborted!
Don't know how to build task 'default'

(See full trace by running task with --trace)

This is because right now, we have defined only the rake test command. Running rake invokes the command default command. We can easily set this command to something else. To set it to the test command, just add

task default: :test

at the end of our Rakefile and try running rake once again. No errors this time!

That’s it for setting up our Rakefile for TDD. You can start writing tests in test folder and follow the Red-Green cycle till your hearts content.

Let me know your thoughts or questions in the comments below!

Share

Tags: , ,