webmock icon indicating copy to clipboard operation
webmock copied to clipboard

Stub request with regex in Url

Open leoplct opened this issue 3 years ago • 3 comments

I want to stub a request where the url contains a string. I found the only solution is to use regex. If I use this

stub_request(:get, Regexp.new("/data?id=#{id}")).to_return(body: data.to_json)

the registered stub will be this. But if fail the matching.

registered request stubs:

stub_request(:get, "/\/data?id=190378479254287/")
stub_request(:get, "/\/data?id=190378479254288/")
stub_request(:get, "/\/data?id=190378479254289/")

leoplct avatar Jan 26 '22 12:01 leoplct

have you verified that these regexes match the url? I find https://rubular.com/ useful for things like that.

E.g. I believe the ? should be escaped or otherwise it means optional in the regexp.

bblimke avatar Jan 26 '22 12:01 bblimke

I've changed to Regexp.new("data\?id=#{id}"))

but still got as

registered request stubs. Those looks as string instead of regular expressions.

       stub_request(:get, "/data?id=190378479254287/")
       stub_request(:get, "/data?id=469564718846159/")
       stub_request(:get, "/data?id=219568718840145/")
       stub_request(:get, "/data?id=92953585819680/")
       stub_request(:get, "/data?id=210300159181943/")

Is there a cleaner way just to say "all URLs that contains this string? It would be easier to read than regex

leoplct avatar Jan 26 '22 12:01 leoplct

@leoplct Regex can be obtuse, but it's powerful and likely not going away. The problem with your particular regex is in the question mark. For some reason Regexp.new drops the backslash and breaks the intent. I recommend always using percent-syntax literals for regexps, preferebbly with single-quote as the delimiter because it rarely pops up in URIs.

Regexp.new("/data\?id=#{id}")
=> /\/data?id=190378479254287/

%r'/data\?id=#{id}'
=> /\/data\?id=190378479254287/

Epigene avatar Mar 15 '22 09:03 Epigene