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

1

6

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.

Matisse answered 31/10, 2018 at 15:40 Comment(0)
M
1

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.

Matisse answered 31/10, 2018 at 15:40 Comment(1)
The big question is, why did it fix the error? I'm using active storage and this is the first time this has happened to me. Not sure if the issue is linked but it would be nice to know 'why' rather than speculation.Hainan

© 2022 - 2024 — McMap. All rights reserved.