How to use webmock regex matcher?
Asked Answered
N

3

30

How to match a URL like:

http://www.example.com/foo/:id/bar
http://www.example.com/foo/1/bar
http://www.example.com/foo/999/bar

stub_request(:post, "www.example.com")

New answered 8/12, 2012 at 2:35 Comment(1)
Are you looking for a Regexp to match the URL patterns?Antiquity
I
12

http://www\..*?\.com/foo/\d+/bar should work for you.

Indelicate answered 9/12, 2012 at 12:24 Comment(1)
@BSeven \. is escaping the . dot character while .*? means any character (the dot character means any character) zero or more times (the * is zero or more times while + is 1 or more times) and make it non-greedy (the question mark ?) so it stops looking as soon as it hits .com.Indelicate
G
39

You can use %r{} instead of // for your regular expression in Ruby to avoid having to escape the forward slashes in URLs. For example:

stub_request(:post, %r{\Ahttp://www.example.com/foo/\d+/bar\z})
Gutter answered 13/9, 2014 at 15:17 Comment(1)
Also, can use many other characters instead of {} to close the regex, for example %r() or %r'' This is helpful because the regex quantity modifier uses curly braces. So if you're trying to match a URL or something with a specific number of characters, like a 36 character API key, use something like parentheses to close the regex.Horsey
V
21

The second argument to stub_request must be a regular expression, not a string.

stub_request(:post, /http:\/\/www.example.com\/foo\/\d+\/bar/)
Valorievalorization answered 17/2, 2014 at 15:31 Comment(0)
I
12

http://www\..*?\.com/foo/\d+/bar should work for you.

Indelicate answered 9/12, 2012 at 12:24 Comment(1)
@BSeven \. is escaping the . dot character while .*? means any character (the dot character means any character) zero or more times (the * is zero or more times while + is 1 or more times) and make it non-greedy (the question mark ?) so it stops looking as soon as it hits .com.Indelicate

© 2022 - 2024 — McMap. All rights reserved.