Skip to content

Instantly share code, notes, and snippets.

@sideshowcoder
Last active May 12, 2018 01:51
Show Gist options
  • 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
@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