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

Rails控制器测试出现uninitialized constant ApplicationController错误求助

问题解决:控制器测试报错uninitialized constant ApplicationController

问题背景

执行迁移操作(删除、重建、迁移并加载数据)后,单元测试可正常运行,但控制器测试触发NameError,提示uninitialized constant ApplicationController。应用本身运行正常,且app/controllers/application_controller.rb文件未被修改,内容如下:

class ApplicationController < ActionController::Base
  include UniversalMethods

解决方案

  • 补全ApplicationController的结束语句
    观察代码发现文件末尾缺少end关键字,这会导致Ruby无法正确解析类定义。虽然开发环境可能因自动加载机制容错,但测试环境加载时会直接失败。修改文件为:

    class ApplicationController < ActionController::Base
      include UniversalMethods
    end
    
  • 清除Bootsnap缓存
    报错涉及Bootsnap的加载缓存,执行命令清除临时缓存:

    bundle exec rails tmp:clear
    
  • 验证测试文件的环境依赖
    确保所有控制器测试文件开头包含:

    require 'test_helper'
    

    同时检查test/test_helper.rb中是否正确初始化Rails环境,确认存在如下代码:

    require File.expand_path('../../config/environment', __FILE__)
    
  • 重新运行测试
    关闭所有测试相关进程后,重新执行控制器测试:

    rails test test/controllers/municipals_controller_test.rb
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:15:33