Slow rspec: The database truncation before test suite takes long time

Problem

I was investigating why rspec execution on local machine takes long time to finish. I've been already using spring, so application loading is fast enough, however, it still takes over 10 seconds to finish every bin/rspec <path> execution.

After some debugging, it turned out rspec spends most of the time in database_cleaner.rb, especially the following code

  # Ensure all sequences are reset at the start of the suite run
  config.before(:suite) do
    setup_database_cleaner
    DatabaseCleaner.clean_with(:truncation)
  end

https://gitlab.com/gitlab-org/gitlab/blob/master/spec%2Fsupport%2Fdatabase_cleaner.rb#L9-12

Interestingly, postgres takes 10 seconds to perform TRUNCATE TABLE on the all tables.

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter - truncate_tables: 1: Elapsed time: 0.0
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter - truncate_tables: 2: Elapsed time: 10.712

Since this block is for ensuring the table is empty, most of the cases it seems not matter on local development. For an experiment, I commented out the block and here are the results

With Truncate in before(suite)

shinya@shinya-MS-7A34:~/workspace/thin-gdk/services/rails/src$ time tre bin/rspec /home/shinya/workspace/thin-gdk/services/rails/src/spec/models/ci/build_spec.rb

real    0m38.748s
user    0m0.349s
sys     0m0.053s

Without truncate in before(suite)

shinya@shinya-MS-7A34:~/workspace/thin-gdk/services/rails/src$ time tre bin/rspec /home/shinya/workspace/thin-gdk/services/rails/src/spec/models/ci/build_spec.rb

real    0m28.769s
user    0m0.372s
sys     0m0.053s

Proposal

Can we make the config.before(:suite) optional that can be bypassed when SKIP_ENSURE_TRUNCATE_IN_SPEC variable is passed?

Edited by 🤖 GitLab Bot 🤖