Jam*_*sen 18 ruby testing url parsing ruby-on-rails
我有一些代码将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
Run Code Online (Sandbox Code Playgroud)
这是一个Rails ActionController::TestCase
,所以我可以访问各种帮助方法; 我找不到合适的人.
当然我可以URI.parse
用来获取URL的params部分,然后将其/&|?/
拆分然后重新拆分'='
,但我希望这已经为我完成了.另外,如果我错过了网址转义或参数解析中的一些模糊规则,该怎么办?有有有什么东西在ActionPack
或ActiveSupport
要做到这一点,但我不能找到它.
谢谢 :)
小智 42
CGI::parse(querystring)
将查询字符串解析为哈希.然后,CGI::unescape(string)
将撤消值中的任何URL编码.
或者,您可以使用Rack::Utils.parse_query
,Rack::Utils.unescape
如果您使用的是最近基于Rack的Rails版本,并希望成为超现代版本.
我不知道任何特定于Rails的帮助器方法来包装这些实用程序函数,但它们使用起来非常简单,并且无论如何CGI或Rack已经加载到Rails环境中.
Bob*_*man 28
你想寻址这一点.
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"
Run Code Online (Sandbox Code Playgroud)
它将自动为您处理所有转义规则,并且它还有一些其他有用的功能,例如不会为完全有效但模糊的URI(如内置URI解析器)抛出异常.