database_cleaner icon indicating copy to clipboard operation
database_cleaner copied to clipboard

Undefined method `rollback' for nil:NilClass

Open nicolasrouanne opened this issue 4 years ago • 1 comments

I'm running around 2000 tests with rspec and ActiveRecord. Every now and then, let's say one out of 5 test suite runs (i.e. 1 out of 10,000 tests), a random test fails with the undefined method 'rollback' for nil:NilClass:

Failure/Error:
  DatabaseCleaner.cleaning do
    example.run
  end

NoMethodError:
  undefined method `rollback' for nil:NilClass

I'm using this configuration (taken from the readme)

DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)

nicolasrouanne avatar Oct 20 '20 07:10 nicolasrouanne

Try this:

require 'active_record'

module RefineRollback
  refine ::ActiveRecord::ConnectionAdapters::TransactionManager do
    def rollback_transaction(transaction = nil)
      @connection.lock.synchronize do
        transaction ||= @stack.pop
        transaction.try(:rollback) && transaction.rollback_records
      end 
    end 
  end 
end

RSpec.configure do |config|
  using RefineRollback
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end 

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end 

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end 

  config.before(:each) do
    DatabaseCleaner.start
  end 

  config.after(:each) do
    DatabaseCleaner.clean
  end 
end

danielpclark avatar Mar 11 '21 15:03 danielpclark