Skip to content

Commit 59334e0

Browse files
authored
feat(test): add Stubs#clear to remove all stubs (#1675)
1 parent 469f25c commit 59334e0

3 files changed

Lines changed: 36 additions & 3 deletions

File tree

docs/adapters/test-adapter.md

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,16 @@ verify the order or count of any stub.
100100
stubs.verify_stubbed_calls
101101
```
102102

103-
After the test case is completed (possibly in an `after` hook), you should clear
104-
the default connection to prevent it from being cached between different tests.
105-
This allows for each test to have its own set of stubs
103+
After the test case is completed (possibly in an `after` hook), you should reset
104+
the stubs so each test starts with its own set. When you hold a reference to the
105+
`Stubs` instance, call `clear` to remove every stub, including consumed ones.
106+
107+
```ruby
108+
stubs.clear
109+
```
110+
111+
Alternatively, if you rely on the default connection, you can clear it to prevent
112+
it from being cached between different tests.
106113

107114
```ruby
108115
Faraday.default_connection = nil

lib/faraday/adapter/test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,14 @@ def options(path, headers = {}, &block)
127127
new_stub(:options, path, headers, &block)
128128
end
129129

130+
# Removes all stubs, including the ones that have already been consumed.
131+
def clear
132+
@stubs_mutex.synchronize do
133+
@stack.clear
134+
@consumed.clear
135+
end
136+
end
137+
130138
# Raises an error if any of the stubbed calls have not been made.
131139
def verify_stubbed_calls
132140
failed_stubs = []

spec/faraday/adapter/test_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,4 +439,22 @@ def make_request
439439
end
440440
end
441441
end
442+
443+
describe '#clear' do
444+
it 'removes pending stubs' do
445+
stubs.clear
446+
expect { connection.get('/hello') }.to raise_error(described_class::Stubs::NotFound)
447+
end
448+
449+
it 'removes already consumed stubs' do
450+
expect(connection.get('/hello').body).to eq('hello')
451+
stubs.clear
452+
expect { connection.get('/hello') }.to raise_error(described_class::Stubs::NotFound)
453+
end
454+
455+
it 'leaves the stubs empty' do
456+
stubs.clear
457+
expect(stubs).to be_empty
458+
end
459+
end
442460
end

0 commit comments

Comments
 (0)