运行 Capybara 时如何配置 puma?

How can I configure puma when running Capybara?

我想在 运行 Capybara 测试时调整 puma 配置。更改 .env、.env.test(我使用 dotenv)或 config/puma.rb 中的设置无效。

在哪里可以更改配置?

Rails 5.1,闹鬼 1.15.0,水豚 2.14.0,美洲狮 2.8.2

通常,对于 Capybara,您可以在 register_server 块中配置服务器。 Capybara 提供的 :puma 服务器定义是

Capybara.register_server :puma do |app, port, host|
  require 'rack/handler/puma'
  Rack::Handler::Puma.run(app, Host: host, Port: port, Threads: "0:4")
end

如果您正在使用 Rails 5.1 系统测试,它会在其中添加一个抽象层,并在其中完成服务器配置 ActionDispatch::SystemTesting::Server#register 定义为

def register
  Capybara.register_server :rails_puma do |app, port, host|
    Rack::Handler::Puma.run(app, Port: port, Threads: "0:1")
  end
end

无论哪种方式,您都应该能够覆盖当前服务器注册之一

Capybara.register_server :rails_puma do |app, port,host|
  Rack::Handler::Puma.run(app, ...custom settings...)
end

或配置您自己的

Capybara.register_server :my_custom_puma do |app, port, host|
  Rack::Handler::Puma.run(app, ...custom settings...)
end

Capybara.server = :my_custom_puma

ApplicationSystemTestCase 中,您可以通过将 options 传递给 setup 中 Rails 使用的默认 :puma 服务器进行配置。

据我所知,这适用于任何选项,但我只使用过

  • Silent: true 使 puma 启动输出静音
  • Thread: '1:1'配置puma进程只使用一个线程

以下是我在 docker 容器内设置 rails 系统测试到 运行 的方法:

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driven_by :selenium, using: :chrome, screen_size: [1400, 1400], options: { url: "http://selenium:4444/wd/hub" }

  def setup
    Capybara.server_host = '0.0.0.0' # bind to all interfaces
    Capybara.server = :puma, { Silent: true, Threads: '1:1' }
    host! "http://#{IPSocket.getaddress(Socket.gethostname)}"
    super
  end
end