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