From 545339fe8ea4b72de520c738fa18037a7826b4c5 Mon Sep 17 00:00:00 2001 From: Ryan Lue Date: Thu, 11 Apr 2019 01:14:34 +0800 Subject: [PATCH] Replace :application_handle spec helper with ApplicationHandleInfo.use method --- lib/application_handle_info.rb | 10 +++++++ spec/lib/application_handle_info_spec.rb | 34 ++++++++++++++++++++++++ spec/support/application_handle_info.rb | 6 +---- 3 files changed, 45 insertions(+), 5 deletions(-) create mode 100644 spec/lib/application_handle_info_spec.rb diff --git a/lib/application_handle_info.rb b/lib/application_handle_info.rb index c63c8627e..27a8dc981 100644 --- a/lib/application_handle_info.rb +++ b/lib/application_handle_info.rb @@ -12,4 +12,14 @@ module ApplicationHandleInfo current.split('.')[1] == 'postmaster' end + + def self.use(name) + raise ArgumentError, 'requires a block' if !block_given? + + orig = current + self.current = name + yield + ensure + self.current = orig + end end diff --git a/spec/lib/application_handle_info_spec.rb b/spec/lib/application_handle_info_spec.rb new file mode 100644 index 000000000..1f8255aca --- /dev/null +++ b/spec/lib/application_handle_info_spec.rb @@ -0,0 +1,34 @@ +require 'rails_helper' + +RSpec.describe ApplicationHandleInfo do + describe '.use' do + it 'requires a block' do + expect { ApplicationHandleInfo.use('foo') } + .to raise_error(ArgumentError) + end + + context 'for a given starting ApplicationHandleInfo' do + before { ApplicationHandleInfo.current = 'foo' } + + it 'runs the block using the given ApplicationHandleInfo' do + ApplicationHandleInfo.use('bar') do + expect(ApplicationHandleInfo.current).to eq('bar') + end + end + + it 'resets ApplicationHandleInfo to its original value' do + ApplicationHandleInfo.use('bar') {} + + expect(ApplicationHandleInfo.current).to eq('foo') + end + + context 'when an error is raised in the given block' do + it 'does not rescue the error, and still resets ApplicationHandleInfo' do + expect { ApplicationHandleInfo.use('bar') { raise } } + .to raise_error(StandardError) + .and not_change { ApplicationHandleInfo.current } + end + end + end + end +end diff --git a/spec/support/application_handle_info.rb b/spec/support/application_handle_info.rb index e3a0cbf56..a63d54c98 100644 --- a/spec/support/application_handle_info.rb +++ b/spec/support/application_handle_info.rb @@ -1,11 +1,7 @@ RSpec.configure do |config| - config.around(:each, :application_handle) do |example| - ApplicationHandleInfo.current = example.metadata[:application_handle] - begin + ApplicationHandleInfo.use(example.metadata[:application_handle]) do example.run - ensure - ApplicationHandleInfo.current = nil end end end