Ruby Database cleaner (MySQL)

Database cleaner helps you clean database for tests

  • Install and config database_cleaner

Gemfile

gem 'database_cleaner'
gem 'sequel'

env.rb

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
DatabaseCleaner.connections.inspect
  • Set transaction as the strategy; however, this works only if the table doesn’t have foreign key constraints
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.start
<dirty the db>
DatabaseCleaner.clean
  • To clean the complete table, clean the db with truncation
DatabaseCleaner.clean_with(:truncation)
  • To ignore foreign key constraints,
connection.run('SET FOREIGN_KEY_CHECKS=0;')
DatabaseCleaner.clean_with(:truncation)
connection.run('SET FOREIGN_KEY_CHECKS=1;')

 

 

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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