The new public before_fork_hook for Rails tests

Parallel testing

Rails can run your tests with multiple processes in parallel to reduce overall time spent on test runs. It's a neat feature and one reason to stay with default Rails testing stack instead of choosing the RSpec framework. And the best part is that it doesn't require any additional setup.

But one of the challenges with parallel testing is managing resources and state before forking test processes. There was no designated public API for executing actions before forking test processes took place. We did have setup and teardown hooks but nothing to hook into just before the forking process starts.

before_fork_hook

Luckily Eileen, the Rails core member, added a specific before_fork_hook recently to address that. The added feature introduces a public API for calling the before fork hooks when using Minitest. We can now define custom actions to be executed before test processes are forked using the parallelize_before_fork method:

class MyRailsTest < ActiveSupport::TestCase
  parallelize_before_fork do
    # perform an action before test processes are forked
  end
end
Author
Josef Strzibny
Hello, I am Josef and I am on Rails since its 2.0 version. I always liked strong conventions and the Rails Omakase docrine. I am author of Kamal Handbook and Test Driving Rails. I think testing should be fun, not a chore.

© Test Driving Rails Blog