Friday, October 09, 2009

Ruby: Testing Rake Tasks

I wrote a rake task for my Rails project, and I figured I should write some tests for it. The rake task just creates a certain file, hence it's easy to test. I looked for some entries on testing rake tasks using RSpec.

This blog post shows how to launch rake from within your test--in process. I couldn't get it to work because "Rake" wasn't loaded. This blog post shows how to refactor your rake code into a library that can be more easily tested. I decided to shell out to rake instead.

After reading about the differences between kernel.exec, kernel.system, %x{}, and backticks, I decided to just use backticks. The code ended up being fairly simple since it doesn't require much setup:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "rake some:task" do
context "subtask" do
it "should create some file containing some stuff" do
begin
`rake some:task:subtask SOME=args`
$?.exitstatus.should == 0
created_file = File.expand_path(File.dirname(__FILE__) + '/../../config/some_subdir/this_got_created.json')
file_contents = File.new(created_file).read()
# Verify the file contents...
ensure
File.unlink(created_file) if File.exist?(created_file)
end
end
end
end
This definitely adds a second or two to my tests, but I'm okay with that.

No comments: