Ruby-on-rails 如何在 Rails 测试中轻松解析带有参数的 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/916067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I easily parse a URL with parameters in a Rails test?
提问by James A. Rosen
I have a some code that embeds a return_toURL into a redirect (like OpenID) that I want to test:
我有一些代码将return_toURL嵌入到我想要测试的重定向(如 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
It's a Rails ActionController::TestCase, so I have access to all sorts of helper methods; I just can't find the right one.
它是一个 Rails ActionController::TestCase,所以我可以访问各种辅助方法;我只是找不到合适的。
Of course I could use URI.parseto get the params part of the URL, then split it on /&|?/and then split again on '=', but I'm hoping this is already done for me. Plus, what if I miss some obscure rule in URL escaping or parameter parsing? There hasto be something in ActionPackor ActiveSupportto do this, but I can't find it.
当然,我可以使用URI.parse获取 URL 的 params 部分,然后将其拆分/&|?/,然后再次拆分'=',但我希望这已经为我完成了。另外,如果我在 URL 转义或参数解析中遗漏了一些晦涩的规则怎么办?有有有什么东西在ActionPack或ActiveSupport要做到这一点,但我不能找到它。
Thanks :)
谢谢 :)
回答by chrismear
CGI::parse(querystring)will parse a querystring into a hash. Then, CGI::unescape(string)will undo any URL-encoding in the value.
CGI::parse(querystring)将查询字符串解析为哈希。然后,CGI::unescape(string)将撤消值中的任何 URL 编码。
Alternatively, you can use Rack::Utils.parse_queryand Rack::Utils.unescapeif you're on a recent Rack-based version of Rails, and want to be super-modern.
或者,如果您使用的是基于 Rack 的最新版本的 Rails,并且想要超级现代Rack::Utils.parse_query,Rack::Utils.unescape则可以使用and 。
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.
我不知道包装这些实用程序函数的任何特定于 Rails 的帮助器方法,但它们使用起来非常简单,而且 CGI 或 Rack 无论如何已经加载到 Rails 环境中。
回答by Bob Aman
You want Addressablefor 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.
它会自动为您处理所有转义规则,并且它还有一些其他有用的功能,例如不会为完全有效但模糊的 URI(如内置 URI 解析器)抛出异常。

