You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7 + Authlogic 6.4.3 控制器测试认证报错求助

Rails 7 + Authlogic 6.4.3 控制器测试认证问题

遇到的错误

  • 创建会话时触发:
Authlogic::Session::Activation::NotActivatedError: You must activate the Authlogic::Session::Base.controller with a controller object before creating objects
  • 尝试使用setup:activate_authlogic时触发:
NoMethodError: undefined method 'activate_authlogic' for #<VideosTest:0x00007f0fb982f0d0>
  • 改用setup块后仍触发第一个错误;调用自定义login辅助方法时触发路由错误:
ActionController::UrlGenerationError: No route matches {:action=>"http://test.host/sesiones", :controller=>"videos", :email=>"a@a.com", :password=>"password"}

当前代码

test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "authlogic/test_case"


class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  #
  # Note: You'll currently still have to declare fixtures explicitly in integration tests
  # -- they do not yet inherit this setting
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

# Define active_authlogic into all setup
class ActionController::TestCase

  setup do
    :activate_authlogic
  end

  def login(user)
    post sesiones_url, :params => { :email => user.email, :password => 'password' }
  end
end

测试代码(VideosTest)

require 'test_helper'

class VideosTest < ActionController::TestCase

  setup do
    @video = video(:one)
  end

  test "should get new" do
    Sesion.create(usuarios(:admin))
    get :new
    assert_response :success
  end
  
end

解决方案

1. 正确激活Authlogic

当前ActionController::TestCase的setup块仅写了符号:activate_authlogic,未执行实际方法。修正方式如下:

class ActionController::TestCase
  # 两种写法任选其一
  setup :activate_authlogic 

  # 或者
  # setup do
  #   activate_authlogic
  # end

  def login(user)
    # 修复路由问题:post方法第一个参数用路径辅助方法,参数结构匹配控制器接收规则
    post sesiones_path, params: { sesion: { email: user.email, password: 'password' } }
  end
end

路由错误原因:sesiones_url生成完整URL,而post方法第一个参数应传入路径(用sesiones_path);同时参数需嵌套在会话模型键下(如sesion[email]),匹配控制器的参数接收逻辑。

2. 直接创建会话(绕过登录请求)

若不想通过HTTP请求模拟登录,可在测试中直接激活会话:

class VideosTest < ActionController::TestCase
  setup do
    @video = video(:one)
    activate_authlogic # 提前激活Authlogic上下文
  end

  test "should get new" do
    Sesion.create(usuarios(:admin))
    get :new
    assert_response :success
  end
end

3. 绕过认证的快捷方式

若仅需跳过认证逻辑测试功能,可直接模拟控制器内部的登录状态:

test "should get new without login" do
  # 假设控制器用@current_usuario判断登录状态
  @controller.instance_variable_set(:@current_usuario, usuarios(:admin))
  # 若控制器有set_current_usuario这类方法,也可直接调用:
  # @controller.set_current_usuario(usuarios(:admin))
  
  get :new
  assert_response :success
end

这种方式无需依赖Authlogic会话创建,直接跳过认证流程。


内容的提问来源于stack exchange,提问作者Ticsup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:53:10