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:
- A specific RSpec Example Group with relevant task initialization and hooks
- Metadata integration to allow flexible declaration of tasks location or Rake file name
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.