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
相关产品推荐
相关产品推荐

