December 16, 2009
FakeWeb is a great way to speed up your tests and remove dependencies on external web services. Using FakeWeb is simple: specify a URL for FakeWeb to respond to, and give it the response you expect from the request. For example:Now FakeWeb will prevent your code from making an actual HTTP request and instead it will return the response you specified. But what if your application makes requests to URLs with query parameters? It would be tedious to register each URL with FakeWeb:
Thankfully, FakeWeb has a (slightly underdocumented) solution for this. Instead of passing a string to
FakeWeb.register_uri, pass it a regular expression (using Ruby’s
%r|| syntax to avoid having to escape forward slashes):
By registering a regular expression, FakeWeb will respond to any HTTP GET request whose URL matches the pattern you’ve supplied. Your test suite can make requests with all different query parameters without having to register each individual URL. This feature adds a lot of flexibility to FakeWeb and makes it feasible to stub out your application’s HTTP requests, even when complex, changing query parameters are involved.