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

Rails6.1测试环境下ActiveStorage::Current.host为nil引发URI错误

Rails 6.1升级后ActiveStorage URL在JS测试中返回nil的问题

环境信息

Rails 6.1.7
Ruby 3.1.2
Rspec 3.12.0
Capybara 3.38.0

问题描述

在启用JavaScript的Capybara/Selenium Chrome驱动中运行测试时,调用ActiveStorage::Blob.url方法获取附件URL,升级至Rails 6.1后出现URL为nil的错误。已调试确认attachment为ActiveStorage::Attached::One且关联了ActiveStorage::Blob,该功能在升级前正常可用。

尝试过的配置方案

  • 在RSpec全局配置中预设host无效:
RSpec.configure do |config|
  config.before(:each) do
    ActiveStorage::Current.host = "https://example.com"
  end
end
  • 在Helper模块中引入ActiveStorage::SetCurrent无效:
module ImagesHelper
  include ActiveStorage::SetCurrent
  def serialised_attachment(attachment)
    {
      downloadUrl:  attachment.url,
      name:         attachment.filename
    }
  end
end
  • 在Helper方法内直接设置host可解决问题,但属于不良实践,无法用于生产环境:
module ImagesHelper
  def serialised_attachment(attachment)
    ActiveStorage::Current.host = "https://example.com"
    {
      downloadUrl:  attachment.url,
      name:         attachment.filename
    }
  end
end

疑问

是否Rails 6.1后测试套件中host的设置逻辑发生了变化?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:05:15