diff --git a/docs/adapters/test-adapter.md b/docs/adapters/test-adapter.md index 3a647946b..bab9e7273 100644 --- a/docs/adapters/test-adapter.md +++ b/docs/adapters/test-adapter.md @@ -100,9 +100,16 @@ verify the order or count of any stub. stubs.verify_stubbed_calls ``` -After the test case is completed (possibly in an `after` hook), you should clear -the default connection to prevent it from being cached between different tests. -This allows for each test to have its own set of stubs +After the test case is completed (possibly in an `after` hook), you should reset +the stubs so each test starts with its own set. When you hold a reference to the +`Stubs` instance, call `clear` to remove every stub, including consumed ones. + +```ruby +stubs.clear +``` + +Alternatively, if you rely on the default connection, you can clear it to prevent +it from being cached between different tests. ```ruby Faraday.default_connection = nil diff --git a/lib/faraday/adapter/test.rb b/lib/faraday/adapter/test.rb index c637d139a..d634fc6d3 100644 --- a/lib/faraday/adapter/test.rb +++ b/lib/faraday/adapter/test.rb @@ -127,6 +127,14 @@ def options(path, headers = {}, &block) new_stub(:options, path, headers, &block) end + # Removes all stubs, including the ones that have already been consumed. + def clear + @stubs_mutex.synchronize do + @stack.clear + @consumed.clear + end + end + # Raises an error if any of the stubbed calls have not been made. def verify_stubbed_calls failed_stubs = [] diff --git a/spec/faraday/adapter/test_spec.rb b/spec/faraday/adapter/test_spec.rb index 117bb7899..619f85d4e 100644 --- a/spec/faraday/adapter/test_spec.rb +++ b/spec/faraday/adapter/test_spec.rb @@ -439,4 +439,22 @@ def make_request end end end + + describe '#clear' do + it 'removes pending stubs' do + stubs.clear + expect { connection.get('/hello') }.to raise_error(described_class::Stubs::NotFound) + end + + it 'removes already consumed stubs' do + expect(connection.get('/hello').body).to eq('hello') + stubs.clear + expect { connection.get('/hello') }.to raise_error(described_class::Stubs::NotFound) + end + + it 'leaves the stubs empty' do + stubs.clear + expect(stubs).to be_empty + end + end end