Rails: How do I write a spec for a route that does a redirect?
-
12-10-2019 - |
Question
I am using Omniauth in my Rails project, and I'd like to hide "/auth/facebook" behind a "/login" route.
In fact, I wrote a route:
match "/login", :to => redirect("/auth/facebook"), :as => :login
and this actually works, i.e. a link to login_path
will redirect to /auth/facebook
.
However, how can I write a (RSpec) spec to test this route (specifically, the redirect)?
Do note that /login
is not an actual action nor method defined in the application.
Thanks in advance!
Solution
Because you didn't provide any detail about your environment, the following example assumes you are using rspec 2.x and rspec-rails, with Rails 3.
# rspec/requests/redirects_spec.rb
describe "Redirects" do
describe "GET login" do
before(:each) do
get "/login"
end
it "redirects to /auth/facebook" do
response.code.should == "302"
response.location.should == "/auth/facebook"
end
end
end
Read the Request Specs section of rspec-rails for more details.
OTHER TIPS
You can also use:
get "/login"
response.should redirect_to(path)
You should use Rack::Test and check the url and the http status code
get "/login"
last_response.status.should == 302
last_response.headers["Location"].should == "/auth/facebook"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow