Ruby Database cleaner (MySQL)

Database cleaner helps you clean database for tests

  • Install and config database_cleaner


gem 'database_cleaner'
gem 'sequel'


require 'database_cleaner'
require 'sequel'
  • DB connection through database_cleaner
connection = Sequel.connect("mysql2://username:password@hostname:port/db_name")
DatabaseCleaner[:sequel].db = connection
  • Alternate option for DB connect
DatabaseCleaner[:sequel, {:connection => Sequel.connect('mysql2://username:password@hostname:port/db_name')}]
  • Check if the connection is ready
  • Set transaction as the strategy; however, this works only if the table doesn’t have foreign key constraints
DatabaseCleaner.strategy = :transaction
<dirty the db>
  • To clean the complete table, clean the db with truncation
  • To ignore foreign key constraints,'SET FOREIGN_KEY_CHECKS=0;')
DatabaseCleaner.clean_with(:truncation)'SET FOREIGN_KEY_CHECKS=1;')




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s