Rails Adds SKIP_TEST_DATABASE_TRUNCATE Flag To Speed Up Multi Process Test Runs

Testing is a crucial part of the development process, especially in large Rails applications with extensive databases.

However, running a comprehensive test suite can often be time-consuming, particularly when dealing with multiple processes and a significant number of database tables.

Why Database Truncation Slows Down Tests

Rails truncates (clearing out) the tables in our test database before running tests to ensure that each test starts with a clean state, free from any data left over by previous tests.

While this ensures test isolation, it can also introduce significant overhead with unnecessary truncation operations especially in applications with a large number of tables.

For instance, imagine an application with 178 tables. If we are running tests across 24 processes, each process might perform truncation for each test, leading to thousands of truncation operations. This redundancy can add a considerable amount of time to our test suite.

ENV[“SKIP_TEST_DATABASE_TRUNCATE”]

Rails offers the ENV[“SKIP_TEST_DATABASE_TRUNCATE”] flag to speed up multi process test runs on large databases.

By setting this environment variable, we can instruct Rails to skip the truncation step between tests when all tests are run within the default transaction. This optimization can save a significant amount of time, particularly for large databases.

# In the command line

SKIP_TEST_DATABASE_TRUNCATE=true bundle exec rspec
#  In test helper file

ENV["SKIP_TEST_DATABASE_TRUNCATE"]=true
#  In .env file

SKIP_TEST_DATABASE_TRUNCATE=true

As the ENV["SKIP_TEST_DATABASE_TRUNCATE"] flag speed up test runs but, it’s important to ensure our tests are still properly isolated and don’t have unintended side effects.

Conclusion

Optimizing our test suite can lead to significant improvements in development speed and efficiency.

The ENV["SKIP_TEST_DATABASE_TRUNCATE"] flag is ideal to speed up multi-process test runs when we have a large database with many tables, by skipping unnecessary database truncations and running the tests within the default transaction.

Note Please be aware that each tests won’t run with a fresh new state with this addition.

This can help significantly speed up our test suite and allows us to focus more on building features and improving our application.

Need help on your Ruby on Rails or React project?

Join Our Newsletter