Test Rake Tasks

后端 未结 6 960
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 18:28

I am developing a ROR app that relies on many custom Rake tasks.

What is the best way to test them?

6条回答
  •  旧时难觅i
    2021-01-31 19:16

    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.

提交回复
热议问题