如何在Rails测试中轻松解析带有参数的URL? [英] How do I easily parse a URL with parameters in a Rails test?

查看:61
本文介绍了如何在Rails测试中轻松解析带有参数的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码将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部分,然后在/&|?/上拆分它,然后在'='上再次拆分,但是我希望已经为我完成了.另外,如果我在URL转义或参数解析中错过了一些晦涩的规则,该怎么办?在ActionPackActiveSupport中有可以执行此操作,但是我找不到它.

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_queryRack::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆