嘿,我目前正在使用内置在rails中的最小测试框架。尝试在我的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方法测试result_from ActionController :: InvalidAuthenticityToken和protect_from_forgery的方法。是否可以用minitest模拟其中的某些内容,请原谅我的经验仅限于基本模型/控制器/视图测试。
这里没有多少但是我想我会为我的ApplicationControllerTest包含类
require 'test_helper'
class ApplicationControllerTest < ActionController::TestCase
test 'invalid access token' do
end
end
最佳答案
我通过像这样测试控制器来做到这一点:
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操作中,该操作将触发我要测试的实际方法。如果一切按计划进行,您可以测试副作用,看看是否有效。希望这可以为您提供足够的信息,以便您可以对其进行破解以适合您的需求。关于ruby-on-rails - 从ApplicationController中的InvalidAuthenticityToken抢救Rails的Minitest,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34002285/