Skip to content

Instantly share code, notes, and snippets.

@sideshowcoder
Last active May 12, 2018 01:51
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sideshowcoder/5891019 to your computer and use it in GitHub Desktop.
Save sideshowcoder/5891019 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

repinel commented Jul 15, 2015

@al Thanks for the tip!

@woto
Copy link

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