Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helper for testing rake tasks in rails using minitest.
require 'test_helper'
# testing rake task app:awesome_report
# defined in file lib/tasks/app/awesome_report.rake
describe 'App::AwesomeReportTaskTest' do
it 'generates the awesomeness report' do
subject.invoke
assert File.exists?('awesomeness_report.csv')
end
end
# require this in test_helper
class RakeTaskTestCase < ActiveSupport::TestCase
before do
require 'rake'
Rake::Task.define_task :environment
load rake_task_load_path
end
private
def subject
Rake::Task[task_name]
end
def rake_task_load_path
"#{_tasks_base_path}/#{_relative_task_file_path}"
end
def task_name
_relative_task_file_path.sub('/', ':').sub(/\.rake$/, '')
end
def _relative_task_file_path
"#{self.class.name.sub(/TaskTest$/, '').underscore}.rake"
end
def _tasks_base_path
File.expand_path("#{Rails.root}/lib/tasks")
end
end
class MiniTest::Spec
register_spec_type(/.*TaskTest/, RakeTaskTestCase)
end
@al

This comment has been minimized.

Copy link

@al al commented Nov 25, 2013

Thanks. You might want to run a Rake::Task.clear in an after block too, otherwise unpleasant stuff can happen to your day.

@repinel

This comment has been minimized.

Copy link

@repinel repinel commented Jul 15, 2015

@al Thanks for the tip!

@woto

This comment has been minimized.

Copy link

@woto woto commented May 12, 2018

Rails 5

require 'rake'
APPNAME::Application.load_tasks
Rake::Task["task_name"].invoke
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment