Using sign_in, in controller spec using devise

Hi,

I have been looking through google for about an hour now and still don’t have a solution.

I am testing to make sure admin users get redirected to the admin dashboard if they are signed in, and back to the login page if they are not, I am trying to use the sign_in method provided by the Devise::TestHelpers.

Can anyone help? This is what I have.

Spec Helper

...
  config.include Devise::TestHelpers, type: :controller
...

Controller Spec

require 'spec_helper'

describe AdminDashboardsController do
  it 'redirects to admin login if the user is not logged in' do
    get :show

    expect(response).to redirect_to new_admin_session_path
  end

  it 'redirects to admin dashboard if the user is logged in' do
    admin = create(:admin)

    @request.env['devise.mapping'] = Devise.mappings[:admin]
    sign_in admin

    get :show

    expect(response).to redirect_to admin_dashboard_path
  end
end

Routes

Shopping::Application.routes.draw do
  devise_for :admins, controllers: {
    sessions: 'admins/sessions',
    passwords: 'admins/passwords',
    unlocks: 'admins/unlocks'
  }
  resource :admin_dashboard, only: [:show]
end

admin_dashboard GET    /admin_dashboard(.:format)      admin_dashboards#show

Controller

class AdminDashboardsController < ApplicationController
  before_filter :authenticate_admin!, only: [:show]

  def show
  end
end

**Error **

1) AdminDashboardsController redirects to admin dashboard if the user is logged in
     Failure/Error: expect(response).to redirect_to admin_dashboard_path
       Expected response to be a <redirect>, but was <200>
     # ./spec/controllers/admin_dashboards_controller_spec.rb:18:in `block (2 levels) in <top (required)>'

Any help is appreciated, I think I have included everything.

Did you restart ur server?

I mean if u r using spork or guard then u need to restart the server again.

@scott I’ve made a sample app with configuration like yours and the sign_in user worked as expected. I didn’t even have to set the devise.mapping as the mapping is guessed from within the sign_in method.

I suggest you play with binding.pry and try to guess why the test is failing. Try restarting the app as @charlieanna suggested.

1 Like

@lenarty I think what was happening, was that the sign_in method is signing me in and taking me to the admin_dashboard_path, and I was then testing for a redirect, when it’s not actually a redirect if I am on the page already so insted I tested for a success.

Does this sound right to you?

Thanks.

1 Like

@scott that sounds about right :slight_smile: you could check the request’s path to check you’re on the page devise should redirect admins to. What I would do if in doubt I’d check devise’s after_sign_in_path_for and see if the test fails. If they do then all is fine.