From 03e2d00a591bb01afee8a69cd2a4d0f162944c65 Mon Sep 17 00:00:00 2001 From: Duncan Brown Date: Fri, 23 Sep 2022 15:50:52 +0100 Subject: [PATCH] Quietly fail init if no database is present Failing loudly under these circs context isn't helpful because it doesn't reflect a problem with the analytics setup; apps in CI often run the asset precompilation step without a database present. --- lib/dfe/analytics.rb | 7 +++++++ spec/dfe/analytics_spec.rb | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/dfe/analytics.rb b/lib/dfe/analytics.rb index cfbc0244..f0905942 100644 --- a/lib/dfe/analytics.rb +++ b/lib/dfe/analytics.rb @@ -79,6 +79,13 @@ def self.configure end def self.initialize! + begin + ActiveRecord::Base.connection + rescue ActiveRecord::ActiveRecordError + Rails.logger.info('No database connection; DfE Analytics not initialized') + return + end + DfE::Analytics::Fields.check! entities_for_analytics.each do |entity| diff --git a/spec/dfe/analytics_spec.rb b/spec/dfe/analytics_spec.rb index 4fc6a188..da16d551 100644 --- a/spec/dfe/analytics_spec.rb +++ b/spec/dfe/analytics_spec.rb @@ -14,6 +14,14 @@ end end + describe 'when no database connection is available' do + it 'recovers and logs' do + allow(ActiveRecord::Base).to receive(:connection).and_raise(ActiveRecord::ConnectionNotEstablished) + allow(Rails.logger).to receive(:info).with(/No database connection/) + expect { DfE::Analytics.initialize! }.not_to raise_error + end + end + describe 'field checks on initialization' do # field validity is computed from allowlist, blocklist and database. See # Analytics::Fields for more details