LoginSignup
22
15

More than 3 years have passed since last update.

Database Cleanerの使い方

Last updated at Posted at 2019-08-16

Database Cleanerとは

Database CleanerとはRubyのデータを削除するためのgemで提供されているパッケージ
今回はRspecテスト実行時に作成したテストデータをテスト終了後にデータベースから削除するために利用

setup方法

Gemfileに追記する 
(テスト環境でのみ利用できればよかったため以下のような記載に)

group :test do
  gem 'database_cleaner'
end

そしてターミナルで以下を実行

$ bundle install

RSpecの場合のサンプルコード

spec_helper.rbに設定をまとめる場合

RSpec.configure do |config|

## 元々のコードは中略 ##

  # テスト全体の前に実行する処理をブロックで記述
  config.before(:suite) do
    # データベースをCleanする方法を'transaction'に指定
    DatabaseCleaner.strategy = :transaction
    # このタイミングで'transaction'でデータベースをCleanしておく
    DatabaseCleaner.clean_with(:truncation)
  end

  # 各exampleの前および後に実行する処理をブロックで記述
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      # ここに処理を記述する
      # ここがexampleの実行タイミング
      example.run
      # ここに処理を記述する ##
    end
  end

end
任意のファイルで設定する場合(transaction)
require 'database_cleaner/active_record'
# strategyを指定
DatabaseCleaner.strategy = :transaction
# databaseを戻したい地点で以下を記述
DatabaseCleaner.start

## ここでdatabaseが汚れる処理を実行

# databaseをcleanしたい地点で以下を記述
DatabaseCleaner.clean
任意のファイルで設定する場合(truncationやDeletion)
require 'database_cleaner/active_record'
# strategyを指定
DatabaseCleaner.strategy = :truncation #または :Deletion

# databaseをcleanしたい地点で以下を記述
DatabaseCleaner.clean

実行順序

↑早い
before(:suite)
before(:all)
before(:each)
after(:each)
after(:all)
after(:suite)
↓遅い

実行タイミング

:suite
 =>rspecコマンド実行時にテスト全体の前または後に呼び出される
:all
 => 各contextの前または後に呼び出される
:each
 =>各exampleの前または後に呼び出される

Strategies

データベースをCleanする方法のことをStrategieと呼び、以下の3種類が準備されている

Transaction

一連の処理をTransactionという単位で囲み、その始点の状態にデータを戻すことで、データベースをCleanする。

Truncation

指定したテーブルに格納されているデータをすべて削除する"TRANCATE TABLE 文"を使用して、データベースをCleanする。テーブルをいったん削除して改めてテーブルを作成する

Deletion

テーブルはそのままにレコードデータを削除する"DELETE 文"を使用して、データベースをCleanする。

データ削除対象テーブルの指定

:truncationのstrategyを使用するときは、
以下のように実行対象(または実行除外対象)のテーブルを指定できる

DatabaseCleaner.strategy = :truncation, {:only => %w[widgets dogs some_other_table]}
DatabaseCleaner.strategy = :truncation, {:except => %w[widgets]}

補足情報

rails_helper.rbファイルに以下のコードが書かれている場合、rspecのテスト時は
before(:each)でtransactionを張ってafter(:each)でrollbackする処理を実行してくれている。

rails_helper.rb
RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

参考文献

https://github.com/DatabaseCleaner/database_cleaner
https://qiita.com/shoichiimamura/items/25942acc1d1bd78ef9c3

22
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
15