bblimke / webmock

Library for stubbing and setting expectations on HTTP requests in Ruby.
MIT License
3.94k stars 555 forks source link

requiring webmock/rspec after webmock somehow breaks tests in rspec #534

Open illegalnumbers opened 8 years ago

illegalnumbers commented 8 years ago

So I have a setup using RSpec. Webmock is required in our spec helper and we recently tried using webmock/rspec as well. After doing a require for webmock/rspec though our test suite is broken for several tests that use webmock to rack requests to a fake object representing an api. It seems they go out and make requests to the actual api instead of our fake. This is very strange behavior since we have a before block that sets net connections to be disabled.

Examples of what I mean

before :all do
    WebMock.disable_net_connect!(allow_localhost: true)
    WebMock.stub_request(:any, /rest.developer.service.com/).to_rack(Fakes::ServiceFake)
    Service::Base.new.login_app # our call to the service
  end

Works fine when in our rails_helper we just have

require 'webmock'

breaks when we do

require 'webmock'
require 'webmock/rspec'
bblimke commented 8 years ago

Please have a look at https://github.com/bblimke/webmock/blob/master/lib/webmock/rspec.rb

WebMock resets all stubs before each example.

Therefore your before :all which is set up once before all examples is not going to work as webmock will destroy that state after first example.

Either use before :each instead of before :all or don't include webmock/rspec but prepare your own config.

illegalnumbers commented 8 years ago

Ok, that makes sense. Is this not documented anywhere that doing the normal require vs the require rspec does that reset? It was a bit jarring having the library work as expected one way and suddenly different under another. Though I do appreciate what's happening under the hood and understand why it's there. I may just have a selective memory if it is documented. The problem we had was just wanting to use all the great RSpec matchers from Webmock; not that we wanted to use the config or setup.

bblimke commented 8 years ago

@bytenel I try to avoid before :all as it often leads to issues, not only with WebMock.

Do you have a suggestion how should it be documented to make it clear and intuitive?