[rails/rails] テストヘルパーの設定をサポートモジュールに集約するリファクタリング
Context
Active Recordのテストスイートにおいて、test/cases/helper.rbにグローバルな設定やヘルパー定数が散在しており、保守性が低下していました。特にQUOTED_TYPE定数がルートレベルで定義されていたことや、PostgreSQL固有の設定、暗号化設定などが一箇所に集中していたことが課題でした。このPRは、これらの設定を機能ごとに分離し、ARTest名前空間配下に整理することで、テストコードの構造を改善します。
Technical Detail
設定の分離と名前空間化
従来はtest/cases/helper.rbに約50行にわたる設定コードが記述されていましたが、以下の4つのサポートモジュールに分割されました。
1. グローバル設定 (support/global_config.rb)
Active Record全体のテスト設定をARTest::GlobalConfigモジュールに集約しました。また、QUOTED_TYPE定数をARTest名前空間内に移動しています。
module ARTest
QUOTED_TYPE = ActiveRecord::Base.lease_connection.quote_column_name("type")
module GlobalConfig
def self.apply
Thread.abort_on_exception = true
ActiveRecord.deprecator.debug = true
ActiveRecord.permanent_connection_checkout = :disallowed
# ... その他の設定
end
end
end
2. アダプター設定 (support/adapter_config.rb)
接続アダプターの登録処理を独立したファイルに分離しました。
ActiveRecord::ConnectionAdapters.register("abstract", "ActiveRecord::ConnectionAdapters::AbstractAdapter", "active_record/connection_adapters/abstract_adapter")
ActiveRecord::ConnectionAdapters.register("fake", "FakeActiveRecordAdapter", File.expand_path("../support/fake_adapter.rb", __dir__))
3. PostgreSQL設定 (support/postgresql_config.rb)
PostgreSQL固有の設定を条件分岐付きで分離しました。
if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.create_unlogged_tables = true
end
4. 暗号化設定 (support/encryption_config.rb)
Active Record Encryptionの設定を独立したモジュールに移動しました。
ActiveRecord::Encryption.configure \
primary_key: "test master key",
deterministic_key: "test deterministic key",
key_derivation_salt: "testing key derivation salt"
ActiveRecord::Encryption.config.extend_queries = true
ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support
ActiveRecord::Encryption::ExtendedDeterministicUniquenessValidator.install_support
QUOTED_TYPEの参照変更
QUOTED_TYPE定数がARTest名前空間に移動したことで、テストコード全体で参照方法が変更されました。
変更前:
where: "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'"
変更後:
where: "comments.body like 'Normal%' OR comments.#{ARTest::QUOTED_TYPE} = 'SpecialComment'"
この変更は、以下のファイルで一貫して適用されています。
-
test/cases/associations/eager_test.rb(5箇所) -
test/cases/associations/has_many_associations_test.rb(4箇所) -
test/cases/associations/join_model_test.rb(1箇所) -
test/cases/base_test.rb(6箇所) -
test/cases/calculations_test.rb(2箇所) -
test/cases/finder_test.rb(1箇所) -
test/cases/inheritance_test.rb(1箇所) -
test/models/comment.rb(1箇所)
ヘルパーファイルの簡潔化
test/cases/helper.rbは、48行の設定コードが削除され、代わりに4行のrequire文で各サポートモジュールを読み込むようになりました。
require "support/global_config"
require "support/adapter_config"
require "support/encryption_config"
ARTest::GlobalConfig.apply
Impact
このリファクタリングにより、以下のメリットが得られます。
- 関心の分離: 機能ごとに設定が分離され、変更時の影響範囲が明確化
-
名前空間の汚染防止:
QUOTED_TYPEがグローバルからARTest名前空間に移動 -
可読性の向上:
helper.rbが簡潔になり、各設定の役割が明確化 - テストの保守性向上: 特定の設定を変更する際に、該当するサポートファイルのみを編集すれば良い