複数のデータベースを扱うRailsアプリをcucumberでテスト

次のようなコードを想定しよう。


class Legacy < ActiveRecord::Base
establish_connection :legacy
self.abstract_class = true
end

class Company < Legacy
end

class Employee < Legacy
end

class Document < ActiveRecord::Base
end

Documentモデルはアプリケーションのメインのデータベースにアクセスし、CompanyとEmployeeモデルは「レガシー」データベースにアクセスしている。

このアプリケーションをcucumberでテストしたい。

しかし、アプリケーションがレガシーデータベースの中身を書き換えると、シナリオごとにデータベースの状態が変わってしまうという問題がある。

この問題を回避するには、features/step_definitionsディレクトリに次のような内容のファイルを置くとよい。


Before do
Legacy.connection.increment_open_transactions
Legacy.connection.begin_db_transaction
end

After do
unless Legacy.connection.open_transactions.zero?
Legacy.connection.rollback_db_transaction
Legacy.connection.decrement_open_transactions
end
end