webmock icon indicating copy to clipboard operation
webmock copied to clipboard

stub_request with "times" should be unregistered after executed

Open tomasdundacek opened this issue 10 years ago • 3 comments

Hello,

recently I've ran into an issue, where I would expect, that stub_request would be unregistered after it's been run the specified number of times.

Is this an issue or is this behavior specified in the example spec below desired?

Thanks in advance for an answer! Cheers, Tomáš

require 'rspec'
require 'webmock/rspec'
require 'net/http'

describe 'Test' do
  it 'test' do

    # !doesn't work!
    stub_request(:get, 'http://www.example.com/test').
      to_return(body: 'valid')
    stub_request(:get, 'http://www.example.com/test').
      to_return(body: 'invalid').times(1)

    # does work
    #stub_request(:get, 'http://www.example.com/test').
    #  to_return(body: 'invalid').times(1).then.
    #  to_return(body: 'valid')


    c1 = Net::HTTP.get(URI('http://www.example.com/test'))
    c2 = Net::HTTP.get(URI('http://www.example.com/test'))

    expect(c1).to eq('invalid')
    expect(c2).to eq('valid')
  end
end

tomasdundacek avatar Feb 26 '15 16:02 tomasdundacek

I agree it is not intuitive.

It's not as much desired, as just not taken into account.

WebMock will keep returning last declared response after all other declared responses have been used.

In that case times(1), at the end, has no effect.

The thing with WebMock is that even stub_request(...) returns a default 200 response. Stub never expires.

This could be changed, but in version 2.0.

bblimke avatar Feb 26 '15 20:02 bblimke

Hello, sorry for bumping this 4 years old issue, but I am using 3.6.2 and this behavior is still there?

stub = stub_request(method, request_path).with(body: '{}').to_return(status: 200, body: "{}").times(1)
poster.fetch # does 1 request
poster.fetch # does 1 request
expect(stub).to have_been_requested.times(1)

fails, two requests are done. But

stub_request(method, request_path).with(body: '{}').to_return(status: 200, body: "{}").times(1)
poster.fetch # does 1 request
poster.fetch # does 1 request

does not fail. Looks like

WebMock will keep returning last declared response after all other declared responses have been used.

So, what has changed in 2.0?

Any thoughts about this behavior? For me there is no point to write separate expectation if I can use times(n) while declaring stub, as test should fail anyway when there is unexpected webrequest

@bblimke @davidbegin

glebsts avatar Sep 06 '19 11:09 glebsts

@glebsts webmock will keep returning the last declared response. times in response chain only makes sense if there are additional responses declared further down the chain. Nothing has changed in this matter since version 1

bblimke avatar Sep 06 '19 11:09 bblimke