How do I easily parse a URL with parameters in a Rails test? How do I easily parse a URL with parameters in a Rails test? ruby ruby

How do I easily parse a URL with parameters in a Rails test?


CGI::parse(querystring) will parse a querystring into a hash. Then, CGI::unescape(string) will undo any URL-encoding in the value.

Alternatively, you can use Rack::Utils.parse_query and Rack::Utils.unescape if you're on a recent Rack-based version of Rails, and want to be super-modern.

I'm not aware of any Rails-specific helper methods that wrap these utility functions, but they're pretty simple to use, and CGI or Rack is already loaded in the Rails environment anyway.


You want Addressable for this.

uri = Addressable::URI.parse("http://example.com/?var=value")uri.query_values # => {"var"=>"value"}uri.query_values = {"one" => "1", "two" => "2"}uri.to_s # => "http://example.com/?two=2&one=1"

It'll automatically handle all the escaping rules for you, and it has some other useful features, like not throwing exceptions for perfectly valid but obscure URIs like the built-in URI parser.