add expect_request to mirror mocha api
I always use mocha and webmock, but they have 2 different apis.
It would be nice for consistency to be able to use expect_request.
It's pretty easy to implement (only supports times, but easy to extend) ... would a PR that adds it be appreciated ?
FYI similar to https://github.com/bblimke/webmock/issues/737 were I went a different approach, but it's more code and does not fit mocha style.
include(Module.new do
def teardown
@expect_request&.each { |request, times| assert_requested request, times: times }
super
end
end)
def expect_request(*args, times: 1)
request = stub_request(*args)
(@expect_request ||= []) << [request, times]
request
end
/cc @lara
@grosser thank you for opening this issue.
WebMock follows arrange-act-assert pattern e.g used by https://site.mockito.org instead of expect-run-verify, used by RSpec or Mocha. The main purpose was to make mock and verify both optional. You can expect a real request without stubbing it or you can stub request without explicitly expecting it.
Now, since Ruby developers are used to do expect-run-verify pattern and mixing two different approaches can lead to less readable tests I'd be keen to follow up on this and find a solution. I'd like the solution to be complete though.
While your suggested solution works for some cases it also has some issues, which could lead to confusion.
E.g. let's say you do the following:
expect_request(:get, "www.example.com", times: 1)
expect_request(:get, "www.example.com", times: 1)
//execute
One would expect two requests to be made, but both expectations will be satisfied, with just one GET request made to to "www.example.com".
This would likely require a more sophisticated expectation registry implemented,
where the verification at the end knows what execution expectations have already been
matched by given request/s from request registry and not allow two expectations
to match the same request. E.g expect_request(:get, "www.example.com", times: 2),
must be matched by exactly 2 requests to "www.example.com" from the request
registry, and no other expect_request is allowed to use these exactly requests.
It would probably make sense to check how this is implemented in Rspec expectations and in Mocha.
I agree that there could be edge-cases, but for those users can fallback to the base stub + assert workflow I'm mostly proposing adding some sugar on top for the common usecases, not rewriting the whole library