Skip to content

Instantly share code, notes, and snippets.

@miry
Last active May 26, 2022 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miry/d8729ae0406256bc0e089a04b84eeea4 to your computer and use it in GitHub Desktop.
Save miry/d8729ae0406256bc0e089a04b84eeea4 to your computer and use it in GitHub Desktop.
Rake task to run minitests in batches
namespace :test do
desc "Parallel tests. Use TEST_WORKERS and TEST_WORKER_NUM." \
"TEST_WORKER_NUM in range from 1..TEST_WORKERS"
task :parallel do
workers = ENV.fetch("TEST_WORKERS", 1).to_i
worker = ENV.fetch("TEST_WORKER_NUM", 1).to_i
buckets = Array.new(workers) { [] }
# Fill the buckets
i = 0
files = Dir["test/*_test.rb"].entries.sort { |f| File.size(f) }
files.each do |f|
i = 0 if buckets.size == i
buckets[i] << f
i += 1
end
if worker < 1 || worker > workers
raise "TEST_WORKER_NUM is not correct: #{worker}." \
"Check that it greater or equal 1 and less or equal TEST_WORKERS: #{workers}"
end
files = buckets[worker - 1].join(" ")
args = "-Ilib:test -r 'rake/rake_test_loader.rb' #{files} -v #{ENV.fetch("TESTOPTS", "")}"
ruby args do |ok, status|
if !ok && status.respond_to?(:signaled?) && status.signaled?
raise SignalException, status.termsig
elsif !ok
status = "Command failed with status (#{status.exitstatus})"
details = ": [ruby #{args}]"
message = status + details
raise message
end
end
end
end

Running tests in batches

  • TEST_WORKERS - Total number of workers or batches. It uses to identify a total number of batches, that would be run in parallel. Default: 1
  • TEST_WORKER_NUM - Specify which batch to run. The value is between 1 and TEST_WORKERS. Default: 1
$ bundle exec rake test:parallel TEST_WORKERS=5 TEST_WORKER_NUM=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment