Testing Rake Tasks in Rails

I recently wrote a rake task to update some values we’ve got stored in the database. The rake task itself isn’t important in this post, but testing it is.

We’ve got many untested rake tasks in the database, so when our senior dev suggested adding a test, I had to build ours from scratch.

I did a bit more whack-a-moling with error messages than I’d hoped, so here’s a template of that test, along with some details that might save you some time, next time you are writing tests for your rake tasks.

We’re in a not-new version of Rails, and using Minitest. I’ve anonymized it. Hope it’s useful!

# test/tasks/rake_task_file_test.rb

require 'test_helper'
require 'rake'

class RakeTaskFileTaskTest < ActiveSupport::TestCase

describe 'namespace:task_name' do

def setup
@tt = Fabricate(:object_with_attributes_i_need_to_change)
ApplicationName::Application.load_tasks if Rake::Task.tasks.empty?
Rake::Task["namespace:task_name"].invoke
end

it "should change 'thing I don't want'" do
@tt.reload
values = @tt.attribute_i_changed
refute_includes values, "thing I don't want"
assert_includes values, "thing I do want"
end

end
end

Notes on the above:

Useful resources

This article was originally posted on my own site.

--

--

Software, rock climbing, books. I love to learn. https://josh.works

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store