I am developing a ROR app that relies on many custom Rake tasks.
What is the best way to test them?
Rake tasks do need testing, especially if you do some batch processing in it. Testing them is quite easy these days:
class CleanExamsTaskTest < ActiveSupport::TestCase
def test_deletes_results_of_old_exams
travel_to Time.zone.parse('2010-07-05 10:00')
@exam.update!(end: Time.zone.parse('2010-07-04 09:59'))
assert_difference -> { @exam.answered_questions.count }, -1 do
capture_io { run_task }
end
end
def test_output
travel_to Time.zone.parse('2010-07-05 10:00')
@exam.update!(end: Time.zone.parse('2010-07-04 09:59'))
assert_output("Exams processed: 1\n") { run_task }
end
private
def run_task
Rake::Task['exams:clean'].execute
end
end
Full example
Tested with Ruby >= 1.9 and Rails 5.2. Uses Minitest
from stdlib
. No other dependencies.