Back to Blog

Rails 6 adds parallel testing

on April 29, 2019
This blog is part of our Rails 6 series.

Rails 6.0 was recently released.

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

1class ActiveSupport::TestCase
2  parallelize_setup do |worker|
3    # setup databases
4  end
5   parallelize_teardown do |worker|
6    # cleanup database
7  end
8
9  # Run tests in parallel with specified workers
10  parallelize(workers: :number_of_processors)
11
12  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
13  fixtures :all
14
15  # Add more helper methods to be used by all tests here...
16end

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

1$ 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.


You might also like

If you liked this blog post, check out similar ones from BigBinary