ruby-on-railsrubyrspecdatabase-cleaner

DatabaseCleaner raising NoMethodError: undefined method `rollback' for nil:NilClass


I have a rails app using rspec and including DatabseCleaner to ensure the test database is clean between each test.

DatabaseCleaner is configured in our spec/rails_helper.rb with

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end

We've been seeing intermittent errors in our ci environment, where a single test will fail with

 1) LibraryHours Required fields Library Hour must have a location
 Failure/Error:
   DatabaseCleaner.cleaning do
     example.run
   end

 NoMethodError:
   undefined method `rollback' for nil:NilClass
 # ./spec/rails_helper.rb:66:in `block (2 levels) in <top (required)>'

We cannot reproduce the error locally with the seed from the rspec run, and are havng real trouble debugging.


Solution

  • So it turns out that one the developers (me) did not understand that the DatabaseCleaner invocation in the rails_helper was already applying to all specs, and added an extra invocation of DatabaseCleaner.clean to one of the spec files. Removing the addiitonal:

     after do
        DatabaseCleaner.clean
      end
    

    fixed the issue.

    I'm guessing it was a race condition caused by the two invocations of DatabaseCleaner.clean being called.