From dea0a5dfee1dc5715c96d6fe1fda52297b019e25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Bu=C5=82at?= Date: Tue, 5 Jan 2016 16:43:45 +0100 Subject: [PATCH] Better error handling in Chewy::Strategy#wrap Passing non-exising strategy to Chewy::Strategy#wrap caused unclear error: "Can't pop root strategy". Now, push and wrap give back better error when strategy is missing. --- lib/chewy/strategy.rb | 10 +++++++--- spec/chewy/strategy_spec.rb | 14 +++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/chewy/strategy.rb b/lib/chewy/strategy.rb index 8284285a6..d3251f301 100644 --- a/lib/chewy/strategy.rb +++ b/lib/chewy/strategy.rb @@ -56,10 +56,10 @@ def pop end def wrap name - push name + stack = push(name) yield ensure - pop + pop if stack end private @@ -72,7 +72,11 @@ def debug string end def resolve name - "Chewy::Strategy::#{name.to_s.camelize}".constantize or raise "Can't find update strategy `#{name}`" + "Chewy::Strategy::#{name.to_s.camelize}".safe_constantize or raise "Can't find update strategy `#{name}`" + rescue NameError => ex + # WORKAROUND: Strange behavior of `safe_constantize` with mongoid gem + raise "Can't find update strategy `#{name}`" if ex.name.to_s.demodulize == name.to_s.camelize + raise end end end diff --git a/spec/chewy/strategy_spec.rb b/spec/chewy/strategy_spec.rb index b15eb2299..7a8e0309a 100644 --- a/spec/chewy/strategy_spec.rb +++ b/spec/chewy/strategy_spec.rb @@ -14,7 +14,7 @@ end describe '#push' do - specify { expect { strategy.push(:unexistant) }.to raise_error(NameError).with_message(/uninitialized constant.*Unexistant/) } + specify { expect { strategy.push(:unexistant) }.to raise_error(RuntimeError).with_message("Can't find update strategy `unexistant`") } specify do expect { strategy.push(:atomic) } @@ -34,6 +34,18 @@ end end + describe '#wrap' do + specify { expect { strategy.wrap(:unexistant) {} }.to raise_error(RuntimeError).with_message("Can't find update strategy `unexistant`") } + + specify do + expect do + strategy.wrap(:urgent) do + expect(strategy.current).to be_a(Chewy::Strategy::Urgent) + end + end.not_to change { strategy.current } + end + end + context 'nesting', :orm do before do stub_model(:city) do