Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | Capybaraテスト用のDBクリア処理を独自実装する

概要

Capybaraテスト用のDBクリア処理を独自実装する

内容

Capybaraでjsを含むテストを行う際のDBクリア処理を独自実装します。
Capybara+RSPec構成の時はDBCleanerで同様の内容を行ったのですが、
Mini::Test(ActiveSupport::TestCase)の際はDBCleanerがうまく動作しなかったため
独自実装してみました。(自分の設定が悪かっただけかも)

ソースコード

test_helper.rb

module ActiveSupport
  class TestCase
    def teardown
      tables = ActiveRecord::Base.connection.tables
      tables.delete "schema_migrations"

      tables.each do |table|
        eval "#{table.singularize.camelize}.connection.execute(\"TRUNCATE TABLE #{table};\")", binding
      end
    end
  end
end

備考

ActiveRecord::Base.connection.tablesでテーブル一覧を取得
・schema_migrationsは削除したくないので削除対象から除外
・残りのテーブルを全てTruncateする
・#{table.singularize.camelize}は複数形モデル名を単数名にしてモデルクラス名に変換している。