Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

ruby - How do I easily parse a URL with parameters in a Rails test?

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

It's a Rails ActionController::TestCase, so I have access to all sorts of helper methods; I just can't find the right one.

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.

Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CGI::parse(querystring) will parse a querystring into a hash. Then, CGI::unescape(string) will undo any URL-encoding in the value.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...