diff --git a/lib/annotate_rb/model_annotator/annotation_decider.rb b/lib/annotate_rb/model_annotator/annotation_decider.rb index 2e8d852f..611199f4 100644 --- a/lib/annotate_rb/model_annotator/annotation_decider.rb +++ b/lib/annotate_rb/model_annotator/annotation_decider.rb @@ -33,6 +33,9 @@ def annotate? warn "Unable to process #{@file}: #{e.message}" warn "\t#{e.backtrace.join("\n\t")}" if @options[:trace] end + rescue ActiveRecord::ConnectionNotEstablished, + ActiveRecord::NoDatabaseError => e + abort "AnnotateRb: Database connection error - #{e.message}" rescue => e warn "Unable to process #{@file}: #{e.message}" warn "\t#{e.backtrace.join("\n\t")}" if @options[:trace] diff --git a/spec/lib/annotate_rb/model_annotator/annotation_decider_spec.rb b/spec/lib/annotate_rb/model_annotator/annotation_decider_spec.rb index cd08cb3f..5ece1253 100644 --- a/spec/lib/annotate_rb/model_annotator/annotation_decider_spec.rb +++ b/spec/lib/annotate_rb/model_annotator/annotation_decider_spec.rb @@ -105,4 +105,46 @@ let(:skip_annotation_prefix) { AnnotateRb::ModelAnnotator::AnnotationDecider::SKIP_ANNOTATION_PREFIX } it { is_expected.to be false } end + + context "when the database is not accessible" do + let(:model) { double("User") } + + context "when ActiveRecord::ConnectionNotEstablished is raised" do + before do + allow(AnnotateRb::ModelAnnotator::ModelClassGetter).to receive(:call) + .and_raise(ActiveRecord::ConnectionNotEstablished) + end + + it "aborts with an error message instead of silently returning false" do + expect { subject }.to raise_error(SystemExit) + .and output(/AnnotateRb: Database connection error/).to_stderr + end + end + + context "when ActiveRecord::NoDatabaseError is raised" do + before do + allow(AnnotateRb::ModelAnnotator::ModelClassGetter).to receive(:call) + .and_raise(ActiveRecord::NoDatabaseError) + end + + it "aborts with an error message instead of silently returning false" do + expect { subject }.to raise_error(SystemExit) + .and output(/AnnotateRb: Database connection error/).to_stderr + end + end + end + + context "when an unexpected error is raised" do + let(:model) { double("User") } + + before do + allow(AnnotateRb::ModelAnnotator::ModelClassGetter).to receive(:call) + .and_raise(RuntimeError, "oops") + end + + it "rescues the error and returns false" do + expect { subject }.to output(/Unable to process #{file}: oops/).to_stderr + expect(subject).to be false + end + end end