Docker上でSystem Specが失敗する

現象

Docker上でRspecを実行すると、

$ cat docker-compose.yml
version: "3"

services:
  app:
    image: xx/customed_ruby
    command:
      略...
      bundle exec rspec
$ docker-compose up

Chromeがクラッシュしている模様。

app_1    |      6.1) Failure/Error: visit "/"
app_1    | 
app_1    |           Selenium::WebDriver::Error::UnknownError:
app_1    |             unknown error: Chrome failed to start: exited abnormally
app_1    |               (unknown error: DevToolsActivePort file doesn't exist)
app_1    |               (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
app_1    |               (Driver info: chromedriver=2.43.600233 (523efee95e3d68b8719b3a1c83051aa63aa6b10d),platform=Linux 4.9.93-linuxkit-aufs x86_64)

環境

原因

コンテナ内でChromeを起動してみると、

root:/# google-chrome
[8:8:1116/072514.158680:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

Running as root without --no-sandbox is not supported!!!

対策

no-sandboxオプションを指定して実行するか、Root以外のユーザーで実行すれば良さそう。

no-sandboxオプションの指定は以下のように行う。

$ cat spec/rails_helper.rb
RSpec.configure do |config|
  
  # 省略...

  # Run system test in headless mode
  config.before(:each) do |example|
    if example.metadata[:type] == :system
      driven_by :selenium, using: :headless_chrome, screen_size: [1280, 800], options: { args: ["headless", "disable-gpu", "no-sandbox", "disable-dev-shm-usage"] }
    end
  end
end