Allow global stubbing (e.g. before :suite)
In Rspec this works:
RSpec.configure do |config|
config.before :each do
WebMock.stub_request(...)
end
end
However this doesn't work:
RSpec.configure do |config|
config.before :suite do
WebMock.stub_request(...)
end
end
I think it would be useful to stub something globally only once in a before :suite.
Because it calls WebMock.reset! in after(:each) block, if you require 'webmock/rspec'.
See https://github.com/bblimke/webmock/blob/master/lib/webmock/rspec.rb#L29.
+1
@VincentZhao do you know why is necessary to reset the mocks after every test (as the source code does)?
@giovannibenussi because we want to have a clean state when entering a new example.
There should be an option to stub globally by disabling WebMock.reset! conditionally.
That way the preferred "each example in a clean state with its own setup" approach is the default, but can be overridden if necessary.
@Epigene Do you have any suggestion how that option to disable reset conditionally could work?
btw. you don't have to include webmock/rspec config. You can define your own config.
Now that I think about it, the functionality could work like this:
- Allow stubs to have optional metadata (maybe they already support something like that),
- Have a before(:all) call that sets up stubs marked as "global"
WebMock.stub_request(metadata: {type: "global"}), - Do not
require 'webmock/rspec', instead roll your own reset withafter(:each) { WebMock.reset!(except: {metadata: "global"}) }to explicitly keep the "global" mocks. - Allow
WebMock.reset!method to receive optional argument for reset exclusions, - Allow
WebMock.reset!method to receive optional argument for reset exclusions with a special:allargument to skip resetting completely.
5th point would be a quick-and-dirty way to skip reset entirely. If last call of WebMock.reset! dictates the behavior, then projects could have this kind of setup:
# in rails_helper.rb
after do
WebMock.reset!
end
# in some spec file
describe "long setup" do
after do
WebMock.reset!(except: :all)
end
end
some news right here? Is this possible? Thanks
yeah, we need this. for sure!
i don't wanna stub the same and same request over and over again?
Has anybody found a workaround and be able to stub things once?
@mejiaej https://www.rubydoc.info/github/bblimke/webmock/WebMock#globally_stub_request-class_method
@mejiaej https://www.rubydoc.info/github/bblimke/webmock/WebMock#globally_stub_request-class_method
Thanks! Not the ideal scenario (I don't want to stub on every example) but this is what works so far.
RSpec.configure do |config|
config.before :each do
WebMock.globally_stub_request { |request|
if request.uri.to_s =~ /my_url/
{ status: 200, body: '{}', headers: {} }
end
}
end
end