RSpec, FakeWeb, Regexp; a gotcha July 6, 2010 at 5:04 pm
In my effort to be a better BDD/TDD (Behavior-Driven and Test-Driven Development) Developer, I’ve been diving into writing apps using RSpec for testing. The nature of my work has me writing test where, in a non-automated-test environment, I would be using web services (SOAP and/or REST) to get and post data. Now, obviously I don’t want to use a live web services to do this, so enter FakeWeb. I won’t go into the details of what FakeWeb is other than it allows me to fake responses to a given HTTP call.
So, I think I’m pretty slick, having found this nifty tool, but I keep getting schooled when I try to use a regular expression to register an HTTP query string like such:
1 2 3 4 5 | FakeWeb.register_uri( :get, %r|http:\/\/example\.com\/search\.html\?query=.*&collection=.*|, :body => file ) My thought is that this will return 'file' every time I request something like:[cc]http://example.com/search.html?query=foo&collection=bar |
. I’d be wrong.
After much monkey-patching-as-debugging of FakeWeb, I find out that when Ruby parses an incoming URI, it’s broken into parts such as protocol, host, path and query (there are more, but you get my point). When FakeWeb tries to match the incoming URI against my regular expression above, it key-sorts the query, so
1 | http://example.com/search.html?query=foo&collection=bar |
1 | becomes http://example.com/search.html?collection=bar&query=foo |
and FakeWeb throws it out as an unregistered URI. Fun!
Simply re-arranging the regular expression in the register call makes it all happy.
1 2 3 4 | FakeWeb.register_uri( :get, %r|http:\/\/example\.com\/search\.html\?collection=.*&query=.*|, :body => file ) |










