On testing rake files

I started to be concerned about how to test Rake files just recently.

There was an issue for one of the gems I wrote. The gem is mostly a bunch of Rake tasks.

Here’s an example of such a task:

  task :create do
    rakefile = File.expand_path('Rakefile', dummy_path)
    command = "rake -f '%s' db:create" % rakefile
    sh(command) unless ENV["DISABLE_CREATE"]
  end

Now following the articles from Thoughtbot and Tyler, and learning how I could write my tests, I tried to put together hopefully the best of both approaches into a gem I could reuse.

I wrote RSpec Rake, which should provide two important things that could help write rake tests easily:

Now using rspec-rake, here’s an example test for the task from above:

# spec/tasks/dummy_create_spec.rb

require 'spec_helper'

describe 'dummy:create' do
  it 'calls rake with db:create task' do
    rakefile = File.expand_path('../../dummy/Rakefile', __FILE__)
    command = "rake -f '%s' db:create" % rakefile
    # An equivalent of mocking `sh` method
    Rake::AltSystem.should_receive(:system).with(command).and_return(true)
    task.invoke
  end
end

Hopefully this will motivate others to write more Rake task tests too.
For more documentation check the Github repository.

 
18
Kudos
 
18
Kudos

Now read this

Moving on

TL;DR: We built an online learning service and now we are open sourcing it. A couple of days ago I decided to open source The Courseware Project. I must say I’m both happy and sad about doing this. Probably because I should have done it... Continue →