Reputation: 935
I am trying to do an assertion for a Rails test that tests a method redirects to a certain URL, however the URL is only partially complete for my assertion as I am not entirely sure what the full path will be. Therefore I am trying to write an assertion for the partial path. This is what I have but I'm not very good with regexes.
assert_match /[#{PAYPAL_CONFIG["url"]}]./, @response.redirect_url
I want it to match the paypal path and then whatever comes after that but I am not sure how to get this right. When I use this regex to match i get an error in my test empty range in char class: /[https:\/\/www.sandbox.paypal.com\/cgi-bin\/webscr?]./
I know my regex is wrong where I am trying to match anything after the paypal url. Can someone help me out please?
I can see the [] brackets act as an or what I want is the specified path and anything after that.
I have changed my assertion to this:
/#{PAYPAL_CONFIG["url"]}.*/
My test passes but I get this warning: WARNING: MiniTest::MINI_DIR was removed. Don't violate other's internals.
Is my regex ok or not? Thanks
Upvotes: 3
Views: 1262
Reputation: 1087
You ought to escape the url before you drop it in the regex.
Something like
/#{Regexp.escape(PAYPAL_CONFIG["url"])}/
would probably be better.
WRT your example, the problem is in the cgi-bin
bit. The regex engine expects a hyphen to express a range of characters, and i-b
is not a legal range, as there is no character both above i and below b.
The reason the version without the square brackets works is because the regexp engine only interprets hyphens as a range of characters inside the brackets, but the regex itself is still going to be messed up.
>> foo = "https:\/\/www.sandbox.paypal.com\/cgi-bin\/webscr?"
=> "https://www.sandbox.paypal.com/cgi-bin/webscr?"
>> /[#{foo}]/
RegexpError: empty range in char class: /[https:\/\/www.sandbox.paypal.com\/cgi-bin\/webscr?]/
from (irb):2
>> /[#{Regexp.escape(foo)}]/
=> /[https:\/\/www\.sandbox\.paypal\.com\/cgi\-bin\/webscr\?]/
>> Regexp.escape(foo)
=> "https://www\\.sandbox\\.paypal\\.com/cgi\\-bin/webscr\\?"
>> foo
=> "https://www.sandbox.paypal.com/cgi-bin/webscr?"
Upvotes: 2