RSpec测试使用GET参数重定向到URL [英] RSpec testing redirect to URL with GET params
问题描述
假设我有一个FoosController
和redirect_to_baz
方法.
class FoosController < ApplicationController
def redirect_to_baz
redirect_to 'http://example.com/?foo=1&bar=2&baz=3'
end
end
我正在用spec/controllers/foos_controller_spec.rb
对此进行测试:
I'm testing this with spec/controllers/foos_controller_spec.rb
:
require 'spec_helper'
describe FoosController, :type => :controller do
describe "GET redirect_to_baz" do
it "redirects to example.com with params" do
get :redirect_to_baz
expect(response).to redirect_to "http://example.com/?foo=1&bar=2&baz=3"
end
end
end
有效.但是,如果有人交换查询字符串参数(例如http://example.com/?bar=2&baz=3&foo=1
),则测试将失败.
It works. However, if someone swaps the query string parameters (e.g. http://example.com/?bar=2&baz=3&foo=1
), the test fails.
我想做类似的事情:
expect(response).to redirect_to("http://example.com/", params: { foo: 1, bar: 2, baz: 3 })
我查看了文档我尝试搜索response.parameters
,但没有找到类似的内容.甚至Hash#to_query
似乎都不能解决这个问题.
I looked at the documentation and I tried searching for response.parameters
, but I didn't find anything like that. Even Hash#to_query
doesn't seem to solve this problem.
任何帮助将不胜感激.
推荐答案
来自文档,预期的重定向路径可以匹配正则表达式:
From the documentation, the expected redirect path can match a regex:
expect(response).to redirect_to %r(\Ahttp://example.com)
要验证重定向位置的查询字符串似乎有些复杂.您可以访问响应的位置,因此您应该可以执行以下操作:
To verify the redirect location's query string seems a little bit more convoluted. You have access to the response's location, so you should be able to do this:
response.location
# => http://example.com?foo=1&bar=2&baz=3
您应该能够像这样提取查询字符串参数:
You should be able to extract the querystring params like this:
redirect_params = Rack::Utils.parse_query(URI.parse(response.location).query)
# => {"foo"=>"1", "bar"=>"2", "baz"=>"3"}
因此,应该很简单地验证重定向参数是否正确:
And from that it should be straightforward to verify that the redirect params are correct:
expect(redirect_params).to eq("foo" => "1", "baz" => "3", "bar" => "2")
# => true
如果您必须多次执行这种逻辑,将所有内容包装到自定义rspec匹配器中肯定会很方便.
If you have to do this sort of logic more than once though, it would definitely be convenient to wrap it all up into a custom rspec matcher.
这篇关于RSpec测试使用GET参数重定向到URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!