Rails Minitest for application_来自ApplicationController中的InvalidAuthenticityToken

时间:2015-11-30 15:38:24

标签: ruby-on-rails testing minitest

嘿,我目前正在使用内置于rails中的minitest框架。尝试在我的ApplicationController中测试一些方法,围绕protect_from_forgery并从InvalidAuthenticityToken异常中恢复。作为参考,我的ApplicationController看起来像:

  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

我正在寻找带有:: exception方法来测试rescue_from ActionController :: InvalidAuthenticityToken和protect_from_forgery。是否可以用minitest模拟其中的一些东西,请原谅我,因为我的经验仅限于基本的模型/控制器/视图测试。

这里不多,但想到我将包括我的ApplicationControllerTest类

require 'test_helper'

class ApplicationControllerTest < ActionController::TestCase

  test 'invalid access token' do

  end

end

1 个答案:

答案 0 :(得分:1)

我通过剔除测试控制器这样做:

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

存根控制器只是ApplicationController的子类,然后我将路由添加到一个makeup动作中,该动作将触发我想要测试的实际方法。如果一切按计划进行,您可以测试副作用,看它是否有效。希望这能为您提供足够的信息,您可以根据自己的需要进行破解。