简体   繁体   中英

Test authentication redirect using Devise and RSpec

I have a sample Rails app that I'm working on so I can start getting familiar with BDD.

Right now I'm using Devise to handle my user authentication.

I have a Task model which requires a user to be logged in in order to access the new, create, edit, and destroy actions.

I have the following code:

requests/tasks_spec.rb

describe "Tasks" do

  it "redirects to sign in for new task if no user logged in" do
    visit new_task_path
    response.should redirect_to(new_user_session_path)
  end

end

Now when I run this test, I expect it to fail because I haven't added any before_filter logic to TasksController. I run the test and it fails.

Now I add the authenticate_user! helper provided by Devise.

tasks_controller.rb

class TasksController < ApplicationController
  before_filter :authenticate_user!, only: [:new, :edit, :create, :destroy]
  ...
end

The tests run and still fails, saying the following:

  1) TasksController redirects to sign in for new task if no user logged in
     Failure/Error: response.should redirect_to(new_user_session_path)
       Expected response to be a <:redirect>, but was <200>

Now when calling visit, since no user was established in the session, I expect the response to be redirected to /user/sign_in. However, I simply get a 200OK back.

What am I missing here? How do I get this test to pass?

Try this:

describe "redirects to sign in for new task if no user logged in" do
  before { post tasks_path }
  specify { response.should redirect_to(new_user_session_path) }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM