Let's say I have a FoosController
with a redirect_to_baz
method.
class FoosController < ApplicationController
def redirect_to_baz
redirect_to 'http://example.com/?foo=1&bar=2&baz=3'
end
end
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
It works. However, if someone swaps the query string parameters (e.g. http://example.com/?bar=2&baz=3&foo=1
), the test fails.
What's the right way of testing this?
I would like to do something like:
expect(response).to redirect_to("http://example.com/", params: { foo: 1, bar: 2, baz: 3 })
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.
Any help would be greatly appreciated.
I had a need for something similar and ended up with this:
Was able to write tests and not worry about query parameter ordering.
Drop the following into ./spec/support/matchers/be_a_similar_url_to.rb
From the documentation, the expected redirect path can match a regex:
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:
You should be able to extract the querystring params like this:
And from that it should be straightforward to verify that the redirect params are correct:
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.
Are you able to use your route helpers rather than a plain string? If so, you can just pass hash params to a route helper and they will be converted to query string params:
Does that help, or are you restricted to using strings rather than route helpers?
Another thought is that you could just assert directly on the values in the params hash rather than the url + query string, since the query string params will get serialized into the params hash...