From 82048021f7da4c69179402645c8138ad6b05ad34 Mon Sep 17 00:00:00 2001 From: Aleksandr Obukhov Date: Fri, 6 Sep 2024 10:34:53 +0200 Subject: [PATCH] Check if Rails is fully initialized --- lib/saml_idp.rb | 2 +- lib/saml_idp/configurator.rb | 2 +- spec/lib/saml_idp/configurator_spec.rb | 29 ++++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/saml_idp.rb b/lib/saml_idp.rb index 1e8532f2..d654fe89 100644 --- a/lib/saml_idp.rb +++ b/lib/saml_idp.rb @@ -9,7 +9,7 @@ module SamlIdp require 'saml_idp/metadata_builder' require 'saml_idp/version' require 'saml_idp/fingerprint' - require 'saml_idp/engine' if defined?(::Rails) + require 'saml_idp/engine' if defined?(::Rails::Engine) def self.config @config ||= SamlIdp::Configurator.new diff --git a/lib/saml_idp/configurator.rb b/lib/saml_idp/configurator.rb index 4998869a..e645f912 100644 --- a/lib/saml_idp/configurator.rb +++ b/lib/saml_idp/configurator.rb @@ -35,7 +35,7 @@ def initialize self.service_provider.persisted_metadata_getter = ->(id, service_provider) { } self.session_expiry = 0 self.attributes = {} - self.logger = defined?(::Rails) ? Rails.logger : ->(msg) { puts msg } + self.logger = (defined?(::Rails) && Rails.respond_to?(:logger)) ? Rails.logger : ->(msg) { puts msg } end # formats diff --git a/spec/lib/saml_idp/configurator_spec.rb b/spec/lib/saml_idp/configurator_spec.rb index 5148a289..067ae87b 100644 --- a/spec/lib/saml_idp/configurator_spec.rb +++ b/spec/lib/saml_idp/configurator_spec.rb @@ -47,5 +47,34 @@ module SamlIdp it 'has a valid session_expiry' do expect(subject.session_expiry).to eq(0) end + + context "logger initialization" do + context 'when Rails has been properly initialized' do + it 'sets logger to Rails.logger' do + stub_const("Rails", Class.new) + allow(Rails).to receive(:respond_to?).with(:logger).and_return(true) + allow(Rails).to receive(:logger).and_return(double("Rails.logger")) + + expect(subject.logger).to eq(Rails.logger) + end + end + + context 'when Rails is not fully initialized' do + it 'sets logger to a lambda' do + stub_const("Rails", Class.new) + allow(Rails).to receive(:respond_to?).with(:logger).and_return(false) + + expect(subject.logger).to be_a(Proc) + end + end + + context 'when Rails is not defined' do + it 'sets logger to a lambda' do + hide_const("Rails") + + expect(subject.logger).to be_a(Proc) + end + end + end end end