Matt
Matt

Reputation: 2843

Rails Minitest for rescue_from InvalidAuthenticityToken in ApplicationController

Hey I am currently using the minitest framework that is built into rails. Trying to test some methods in my ApplicationController around protect_from_forgery and recovering from InvalidAuthenticityToken exceptions. For reference my ApplicationController looks like:

  class ApplicationController < ActionController::Base

      # Prevent CSRF attacks by raising an exception.
      # For APIs, you may want to use :null_session instead.
      protect_from_forgery with: :exception

      rescue_from ActionController::InvalidAuthenticityToken, with: :handle_invalid_token

     def access_denied(exception)
       redirect_to root_path, :alert => exception.message
     end

      protected

        def handle_invalid_token
          flash[:alert] = I18n.translate('devise.failure.invalid_token')
          redirect_to new_user_session_path
        end
   end

I am looking for away to test both the rescue_from ActionController::InvalidAuthenticityToken and the protect_from_forgery with: :exception methods. Is it possible to mock some of these things up with minitest, forgive me for my experience is limited to just basic model/controller/view testing.

Not much here but figured i would include the class for my ApplicationControllerTest

require 'test_helper'

class ApplicationControllerTest < ActionController::TestCase

  test 'invalid access token' do

  end

end

Upvotes: 1

Views: 805

Answers (1)

CWitty
CWitty

Reputation: 4526

I did this by stubbing out a testing controller like so:

class StubController < ApplicationController

  def authenticate_user
    authenticate_user!
    head 200
  end

  def authenticate_user_invalid
    authenticate_user!
  end
end

Rails.application.routes.disable_clear_and_finalize = true

# Create a new route for our new action
Rails.application.routes.draw do
  get 'authenticate_user', to: 'stub#authenticate_user'
  get 'authenticate_user_invalid', to: 'stub#authenticate_user_invalid'
end

class StubControllerTest < ActionController::TestCase

   test 'authenticate_user sets current_user if valid user token and email' do
    user = users(:authenticatable_user)
    @request.headers['Authorization'] = "Token token=#{user.token},email=#{user.email_address}"

    get :authenticate_user
    assert_equal user, assigns(:current_user)
  end
end

The stub controller just subclasses the ApplicationController which I then add routes to the a madeup action that will trigger the actual method I want to test. If everything goes as planned you can test the side effects to see if it worked. Hopefully this gives you enough info that you can hack it to work for your needs.

Upvotes: 1

Related Questions