0

For controllers that assume a user to be already authenticated, how should I go about writing my tests?

I probably don't need to keep testing the login feature, so is it best to just inject a user or whatever my authentication assumes somehow?

My application_controller includes a module "current_user".

module CurrentUser
  def self.included(base)
    base.send :helper_method, :current_user
  end

  def current_user
    ... # returns a User model instance
  end
end

class ApplicationController < ActionController::Base
  include CurrentUser

Then I have an admin controller which has a before_action method that makes sure the current_user is present.

3
  • Devise or no devise? include CurrentUser makes me think no devise. Commented May 28, 2016 at 19:31
  • @fbelanger no devise, custom authentication. Commented May 28, 2016 at 20:43
  • How are you checking that the user has been authenticated? Couldn't you just create a method to sign in, similar to devise? Commented May 28, 2016 at 20:45

1 Answer 1

1

You can easily achieve this by writing a concern, and include to every spec which is a controller, in this concern we support some utility methods to login to the system.

So the code will be like:

spec/support/controller_authentication_helper.rb

module ControllerAuthenticationHelper extend ActiveSupport::Concern
  module ClassMethods
    def login_user
      before do
        # I expect you are using Devise here, if not, just modify below line
        request.env['devise.mapping'] = Devise.mappings[:user]
        @current_user = FactoryGirl.create(:user, :confirmed, :verified)
        sign_in @current_user
      end
    end
  end
end

RSpec.configure do |config|
  config.include ControllerAuthenticationHelper, type: :controller
end

So now the test will be easy like:

require 'rails_helper'

describe MyController, type: :controller do
  # Use this method to login
  login_user
  # Now you can access current_user anywhere in your test
end

Now everything becomes simple! The idea comes from this source code of Devise

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.