Lester Peabody
Lester Peabody

Reputation: 1888

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?

Upvotes: 4

Views: 1703

Answers (1)

Thanh
Thanh

Reputation: 8604

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

Upvotes: 2

Related Questions