simpler rake task testing
Aug 15, 2025
thoughtbot wrote this interesting post on testing rake tasks. inspired by this, i dug into the rake source code and came up with this simpler approach.
shared_context 'rake' do
require 'rake'
let(:rake) { Rake::Application.new }
let(:task_name) { self.class.top_level_description }
let(:task_path) { "lib/tasks/#{task_name.split(":").first}" }
subject { rake[task_name] }
around do |example|
Rake.with_application(rake) do
Rails.application.load_tasks
subject.prerequisites.each do |prerequisite|
rake[prerequisite].clear
end
example.run
end
end
endthe generic part of my test is like so:
include_context 'rake'
it 'has a db:reset prerequisite' do
expect(subject.prerequisites).to include('db:reset')
end