Ruby on Rails生产环境报错:uninitialized constant Mail::TestMailer (NameError)
解决Rails生产环境
uninitialized constant Mail::TestMailer错误 问题背景
生产环境启动Rails应用时触发NameError,提示uninitialized constant Mail::TestMailer,但应用未使用任何邮件服务,application_mailer.rb为默认未修改状态,报错栈指向ActionMailer的加载逻辑。
可能原因及解决步骤
1. 修正生产环境邮件投递配置
如果config/environments/production.rb中错误将邮件投递方式设为:test,会触发加载仅测试环境可用的Mail::TestMailer。
- 打开
config/environments/production.rb,查找并修改如下配置:# 错误配置 # config.action_mailer.delivery_method = :test # 替换为生产环境配置(无需邮件功能可设为禁用) config.action_mailer.perform_deliveries = false config.action_mailer.raise_delivery_errors = false
2. 排除Mailers目录自动加载
若完全不需要邮件功能,可在config/application.rb中禁用app/mailers目录的自动加载:
# 针对Zeitwerk加载器配置 Rails.autoloaders.main.ignore("#{Rails.root}/app/mailers")
3. 清理依赖缓存并重新安装
依赖损坏或加载异常可能导致该问题,执行以下命令:
bundle clean --force bundle install --deployment --without development test
4. 清除Bootsnap缓存
Bootsnap缓存残留可能引发加载逻辑异常,清理缓存:
rm -rf tmp/cache/bootsnap*
5. 确认Mail gem版本兼容性
ActionMailer依赖mail gem,确保其与Rails 6.1.7兼容。可在Gemfile中指定兼容版本:
gem 'mail', '~> 2.7.1'
执行bundle install完成版本更新。
内容的提问来源于stack exchange,提问作者John Coday
相关产品推荐
相关产品推荐

