ruby-on-rails `ActiveStorage:: www.example.com ` in test environment(RSpec)返回nil,导致`URI::InvalidURIError`

ibps3vxo  于 2023-05-02  发布在  Ruby
关注(0)|答案(1)|浏览(107)
Rails 6.1.7
Ruby 3.1.2
Rspec 3.12.0
Capybara 3.38.0

在运行一些测试时,我调用ActiveStorage::Blob.url方法来检索所述附件的URL。升级到Rails 6后1我得到了一个错误,URL为nil。测试在Capybara/Selenium Chrome驱动程序中运行,并启用了Javascript。
调用的方法位于helper模块中:

module ImagesHelper
  def serialised_attachment(attachment)
    {
      downloadUrl:  attachment.url,
      name:         attachment.filename
    }
  end
end

调试时,我可以确认attachmentActiveStorage::Attached::One,并且有一个关联的ActiveStorage::Blob。这在升级之前是有效的。
我发现了一些问题,比如这个https://github.com/rails/rails/issues/40855,我试图在RSpec配置中预置主机。
这不起作用:

RSpec.configure do |config|
  config.before(:each) do
    ActiveStorage::Current.host = "https://example.com"
  end
end

这显然是行不通的:

module ImagesHelper
  include ActiveStorage::SetCurrent
  def serialised_attachment(attachment)
    {
      downloadUrl:  attachment.url,
      name:         attachment.filename
    }
  end
end

这确实有效,但是不好的做法,在生产中不可行:

module ImagesHelper
  def serialised_attachment(attachment)'
    ActiveStorage::Current.host = "https://example.com"
    {
      downloadUrl:  attachment.url,
      name:         attachment.filename
    }
  end
end

我的结论是,在测试套件中的某个地方,主机的设置与Rails 6不同。一号?

w1jd8yoj

w1jd8yoj1#

我让ActiveStorage,Rspec,Capybara/Selenium等一起工作,这样做:

# config/environments/test.rb
Rails.application.routes.default_url_options = { :host => 'localhost', :port => 3000 }

# spec/rails_helper.rb
Capybara.configure do |config|
  config.app_host = 'http://localhost'
  config.server_port = 3000
end

例如,在RSpec系统规范中,我可以运行:

RSpec.describe "Resources", type: :system do
  # ...
  it "should work" do
    expect(page).to have_css("img[src*='#{url_for(@model.attached_image.variant(:thumb))}']")
  end
end

相关问题