← Back to Upcase

Testing current_user in application_controller


(Jonathan twaddell) #1

In my application_controller I have:

  def current_user
    @current_user ||= User.find_by_auth_token(session[:auth_token]) if session[:auth_token]
  end

and the spec:

require 'spec_helper'

describe ApplicationController do
  it 'should check_cred', task057: true do
    user=FactoryGirl.create(:user)
    user.auth_token='abc123'
    user.save
    request.session['auth_token']='abc123'
    returned_user=controller.send(:current_user) # not sure about this
    returned_user.id.should eq(user.id)  end
end

It passes but is there a better way? Or should this even be tested (current_user is implicitly tested via some auth specs to a specific resource)?

thx

thx - can’t reply; make sense


(Adarsh Pandit) #2

Two things:

  1. You can use FG to create the specific User you want in one line:

    describe ApplicationController do
    it ‘should check_cred’, task057: true do
    user=FactoryGirl.create(:user, auth_token: ‘abc123’)

  2. I believe you can do this:

    it ‘sets the current user’ do
    user=FactoryGirl.create(:user, auth_token: ‘abc123’)

     sign_in_as(user)
    
     expect(current_user).to eq user
    

    end

    /spec/support/authentication.rb

    def sign_in_as(user)
    @controller.current_user = user
    end

Then test the other logic path.

Hope this helps!