Rails 6 adds parallel testing

Amit Choudhary

Amit Choudhary

April 29, 2019

This blog is part of our  Rails 6 series.

We frequently think about how good it would be if we could run tests in parallel on local so there would be less wait time for tests to be completed. Wait times increase considerably when the count of tests are on the higher side, which is a common case for a lot of applications.

Though CI tools like CircleCi and Travis CI provide a feature to run tests in parallel, there still wasn't a straightforward way to parallelize tests on local before Rails 6.

Before Rails 6, if we wanted to parallelize tests, we would use Parallel Tests.

Rails 6 adds the parallelization of tests by default. Rails 6 added parallelize as a class method on ActiveSupport::TestCase which takes a hash as a parameter with the keys workers and with. The worker key is responsible for setting the number of parallel workers. The default value of the worker key is :number_of_processors, which finds the number of processors on the machine and sets it as the number of parallel workers. with takes two values - :processes, which is the default one, and :threads as a value.

Rails 6 also added two hooks - parallelize_setup, which is called before the processes are forked, and parallelize_teardown, which is called after the processes are killed. Rails 6 also handles creation of multiple databases and namespacing of those databases for parallel tests out of the box.

If we want to disable parallel testing, we can set the value of workers as 1 or less.

Rails 6.0.0.beta2

class ActiveSupport::TestCase
  parallelize_setup do |worker|
    # setup databases
  end
   parallelize_teardown do |worker|
    # cleanup database
  end

  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

Rails 6 also provides an environment variable PARALLEL_WORKERS to set the number of parallel workers on runtime.

$ PARALLEL_WORKERS=10 bin/rails test

Here is the relevant pull request for adding parallelize and pull request for setting number of processors as default workers count.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.