gpt4 book ai didi

ruby-on-rails - ApplicationController 中用于 rescue_from InvalidAuthenticityToken 的 Rails Minitest

转载 作者:行者123 更新时间:2023-11-28 20:40:44 25 4
gpt4 key购买 nike

嘿,我目前正在使用 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

我正在寻找方法来测试 rescue_from ActionController::InvalidAuthenticityToken 和 protect_from_forgery with::exception 方法。是否可以用 minitest 模拟其中的一些东西,请原谅我的经验仅限于基本模型/ Controller / View 测试。

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

require 'test_helper'

class ApplicationControllerTest < ActionController::TestCase

test 'invalid access token' do

end

end

最佳答案

我通过像这样删除一个测试 Controller 来做到这一点:

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

stub Controller 只是 ApplicationController 的子类,然后我将路由添加到将触发我想要测试的实际方法的虚构操作。如果一切按计划进行,您可以测试副作用以查看其是否有效。希望这能为您提供足够的信息,您可以对其进行破解以满足您的需求。

关于ruby-on-rails - ApplicationController 中用于 rescue_from InvalidAuthenticityToken 的 Rails Minitest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34002285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com