如何在Rails测试中使用参数轻松解析URL?
我有一些代码将return_to
URL嵌入到我想测试的重定向(如OpenID)中:
def test_uses_referrer_for_return_to expected_return_to = 'http://test.com/foo' @request.env['HTTP_REFERER'] = expected_return_to get :fazbot # @response.redirected_to looks like http://service.com?...&return_to=[URI-encoded version of URL above]&... encoded_return_to = (something_here)[:return_to] assert_equal expected_return_to, URI.unencode(encoded_return_to) end
它是一个Rails ActionController::TestCase
,所以我可以访问各种辅助方法; 我找不到合适的人。
当然我可以使用URI.parse
获取URL的params部分,然后将其拆分为/&|?/
然后再次拆分为'='
,但我希望这已经为我完成了。 另外,如果我错过了URL转义或参数解析中的一些模糊规则,该怎么办? 必须在ActionPack
或ActiveSupport
中执行此操作,但我无法找到它。
谢谢 :)
CGI::parse(querystring)
将查询字符串解析为哈希。 然后, CGI::unescape(string)
将撤消值中的任何URL编码。
或者,您可以使用Rack::Utils.parse_query
和Rack::Utils.unescape
如果您使用的是最近的基于机架的Rails版本,并且想要超现代。
我不知道任何包含这些实用程序函数的Rails特定辅助方法,但它们使用起来非常简单,并且无论如何CGI或Rack已经加载到Rails环境中。
你想要解决这个问题。
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"
它会自动为您处理所有转义规则,并且它还有一些其他有用的function,例如不会为完全有效但模糊的URI(如内置URI解析器)抛出exception。