Test Rake Tasks Like a BOSS

Testing Rake tasks is one of the most painful things I do as a Ruby developer.
Even after extracting all the code out into a separate class (which helps a
lot), I still want to make sure I test that the right classes got called
correctly with the right arguments.

I wanted the subject to be the task, where I could call invoke, check its
prerequisites, etc.

describe "cron:hourly" do
its(:prerequisites) { should include("reports:users") }
end
describe "reports:users" do
before { ReportGenerator.stubs(:generate) }
its(:prerequisites) { should include("environment") }
it "generates the report" do
subject.invoke
ReportGenerator.should have_received(:generate).with()
end
end

RSpec has shared contexts, so I set off to find an easy, straightforward way
to test Rake tasks.

This shared context is doing a lot, so I’ll walk through some of the odd areas
and explain what’s happening.

The second let (task_name) is grabbing the top level description. That
means it’ll use the text we pass to describe to calculate the task we’re going
to run.

describe("reports:user") { } # subject is Rake::Task["reports:user"]

task_path is the path to the file itself, relative to Rails.root. We can
infer path based off of the description, so for the describe above, it’ll
assume the rake task is in lib/tasks/reports.rake.

Thirdly, loaded_files_excluding_current_rake_file - this requires a bit of
explanation, even with that really descriptive method name. Rake is kind of a
pain in certain cases; The rake_requiremethod
takes three arguments: the path to the task, an array of directories to look
for that path, and a list of all the files previously loaded. rake_require
takes loaded paths into account, so we exclude the path to the task we’re
testing so we have the task available. This only matters when you’re running
more than one test on a rake task, but there’s no harm in doing this every
time we test so that there aren’t odd edge cases out there.

Finally, I define the :environment task (which most tasks defined in a Rails
app will have as a prerequisite, since it’ll load the Rails stack for
accessing models and code within lib without any additional work.

That’s the shared context in a nutshell; here’s what it allows us to do.

Some people may say, “This is overkill! I tested the classes in other areas!”
To me, that’s just like saying, “I’ve written unit and functional tests so I
don’t need to write integration tests.” If you have a rake task that needs to
be run (cron on Heroku, for example), would you leave that code untested? I
wouldn’t.

Have you extracted out a pattern for testing Rake tasks? I’d love to hear
about it; maybe a patch to RSpec is in order!

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.