Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql2::Error: This connection is in use by

We are getting the following error randomly in our test suite with database cleaner. We are using database cleaner in combination with the following two code snippets that I think are related:

Error:

Mysql2::Error: This connection is in use by: #<Thread:0x00000017bbf2f8 sleep>: TRUNCATE TABLE `cr_contacts`;

Shared DB Connection (The likely cause)

class ActiveRecord::Base
  mattr_accessor :shared_connection
  @@shared_connection = nil

  def self.connection
    @@shared_connection || retrieve_connection
  end
end

# Forces all threads to share the same connection. This works on
# Capybara because it starts the web server in a thread.
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
like image 372
jwg2s Avatar asked Jun 11 '13 17:06

jwg2s


1 Answers

The error is telling you DB cleaner wants to do truncation while other thread is still using the connection. This probably happens in your integration tests with selenium.

It looks like you are using 2 mechanisms for database cleaning:

  • transactional fixtures with shared connections patch
  • truncation with database cleaner

This is not ok. To use DB cleaner, turn off transactional fixtures and remove the shared connection patch. I suggest configuring it the way it is described in this great article by Avdi Grimm: http://devblog.avdi.org/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/

like image 141
jurglic Avatar answered Oct 10 '22 17:10

jurglic