Last Updated: February 25, 2016
· felipeelias

Cut down some seconds of your spec suite by removing database_cleaner

The gem database_cleaner is a beast and may eat some seconds out of your rspec test suite. By using a simpler approach you can save up some time.

Here's how:

RSpec.configure do |config|
  config.around do |example|
    # For examples using capybara-webkit for example.
    # Remove this if you don't use it or anything similar
    if example.metadata[:js]
      ActiveRecord::Base.connection.execute("TRUNCATE #{ActiveRecord::Base.connection.tables.join(',')} RESTART IDENTITY")
      ActiveRecord::Base.transaction do
        raise ActiveRecord::Rollback

The gist here.

The check for :js environment is necessary if you use capybara-webkit.

Many thanks to @brandonhilkert for pointing it out here.

With this change, my suite got 40% faster!!


8 Responses
Add your response

Thanks Felipe, my suite got a 32% faster with this little change.

over 1 year ago ·

Hey, I will check if that improves my suite!

I did a small change due to foreign keys in my database:

I will post the improvement ASAP.

over 1 year ago ·

@sobrinho thanks! I'm keeping it as a gist here

over 1 year ago ·

@felipeelias improved only from 38m36 to 37m02 :(

over 1 year ago ·

:( @sobrinho have you tried to run truncation only for javascript examples? In your pastie it was for request type...

over 1 year ago ·

@felipeelias my application only works with javascript.

There is no complex javascript (only jQuery and jQuery UI) but it have masked inputs, date pickers and modals in almost every screen.

I think that's the cause of my slow suite and not the database :(

over 1 year ago ·

@sobrinho oh shoot! :-(

over 1 year ago ·

i'm using single connection method:
Then i can use rollback even in integration tests with capybara (with the code above or simply config.use_ transactional_ fixtures = true
Am I missing anything?

over 1 year ago ·