如何在 Rails 测试中轻松解析带有参数的 URL? [英] How do I easily parse a URL with parameters in a Rails test?
问题描述
我有一些代码将 return_to
URL 嵌入到我想测试的重定向(如 OpenID)中:
I have a some code that embeds a return_to
URL into a redirect (like OpenID) that I want to test:
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
,所以我可以访问各种辅助方法;我就是找不到合适的.
It's a Rails ActionController::TestCase
, so I have access to all sorts of helper methods; I just can't find the right one.
当然我可以使用 URI.parse
来获取 URL 的 params 部分,然后在 /&|?/
上拆分它,然后在 /&|?/
上再次拆分code>'=',但我希望这已经为我完成了.另外,如果我在 URL 转义或参数解析中遗漏了一些晦涩的规则怎么办?必须在 ActionPack
或 ActiveSupport
中有一些东西来做到这一点,但我找不到它.
Of course I could use URI.parse
to 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 has to be something in ActionPack
or ActiveSupport
to do this, but I can't find it.
谢谢:)
推荐答案
CGI::parse(querystring)
会将查询字符串解析为哈希.然后,CGI::unescape(string)
将撤销值中的任何 URL 编码.
CGI::parse(querystring)
will parse a querystring into a hash. Then, CGI::unescape(string)
will undo any URL-encoding in the value.
或者,如果您使用的是最新的基于 Rack 的 Rails 版本,您可以使用 Rack::Utils.parse_query
和 Rack::Utils.unescape
,并且想要超现代.
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.
我不知道包装这些实用程序函数的任何特定于 Rails 的帮助方法,但它们使用起来非常简单,而且 CGI 或 Rack 无论如何已经加载到 Rails 环境中.
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 测试中轻松解析带有参数的 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!