Browse Source

Replace :application_handle spec helper with ApplicationHandleInfo.use method

Ryan Lue 6 years ago
parent
commit
545339fe8e

+ 10 - 0
lib/application_handle_info.rb

@@ -12,4 +12,14 @@ module ApplicationHandleInfo
 
 
     current.split('.')[1] == 'postmaster'
     current.split('.')[1] == 'postmaster'
   end
   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
 end

+ 34 - 0
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

+ 1 - 5
spec/support/application_handle_info.rb

@@ -1,11 +1,7 @@
 RSpec.configure do |config|
 RSpec.configure do |config|
-
   config.around(:each, :application_handle) do |example|
   config.around(:each, :application_handle) do |example|
-    ApplicationHandleInfo.current = example.metadata[:application_handle]
-    begin
+    ApplicationHandleInfo.use(example.metadata[:application_handle]) do
       example.run
       example.run
-    ensure
-      ApplicationHandleInfo.current = nil
     end
     end
   end
   end
 end
 end