bblimke / webmock

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

Way to specify custom request signature snippets #800

Open leecunliffe opened 5 years ago

leecunliffe commented 5 years ago

For binary protocols, the default stubbing instructions are hard to read and not very helpful. For example:

       You can stub this request with the following snippet:

       stub_request(:post, "https://test.host/services/..."). 
         with(      
           body: "\n\x03123\x10\n\x10\t\x10\x0E\x10\x1A\x18\x02",

I have a work-around for a large project by monkey-patching WebMock::NetConnectNotAllowedError and switching to some custom code based on the Content-Type header.

Would you be open to a PR that added a way to specify a custom handler for the output here? That would allow my work-around to be cleaner, and would allow others to easily make similar improvements.

It might be a little involved because the message is spread across RequestSignature and also RequestSignatureSnippet. Just want to check you would be open to this before opening a PR.

bblimke commented 5 years ago

@yellow-beard thank you for the suggestion. If the solution is easy and intuitive then I'm interested. It would be ideal to have a have a generic solution that works for everyone, but I'm not sure that it's possible.

Perhaps you can share how the final API would look like, with an example, before implementing it.

leecunliffe commented 5 years ago

@bblimke A way to specify a custom class to be used instead of StubRequestSnippet would be sufficient.

The public API could be:

Webmock.stub_request_snippet_class = MyCustomClass

Ended up putting together a branch to make sure this would work:

https://github.com/bblimke/webmock/compare/master...yellow-beard:custom-StubRequestSnippet

bblimke commented 5 years ago

@yellow-beard to be honest, you could simply reopen StubRequestSnippet class and change it. Assigning custom class brings the same risk here as reopening and since there is not really any predefined API for StubRequestSnippet, people would still have to know how to implement it.

leecunliffe commented 5 years ago

@bblimke that's what I'm currently doing :)

My hope is that having an official way to do this gives us some guarantee that our approach won't be broken in future releases. For example if StubRequestSnippet was renamed, or was broken in to multiple classes.

But good point that the API is only defined by the StubRequestSnippet class, and maybe the extra complexity isn't worth it.