83707


下記の記事を参考にdockerで環境構築しました。  
[【動画付き】Everyday RailsのサンプルアプリをRails
6で動かす際に必要なテストコードの変更点](https://blog.jnito.com/entry/2019/10/25/053521)

dockerのイメージがrubyしか入っていないので、下記の記事を参考にrubyのイメージとgoogle
chromeのイメージでコンテナを作成してremoteで操作するようにしました。

[Failed to find Chrome binary
について](https://qiita.com/yusuke_mrmt/items/4e38d031ea49cdd8834d)

capybara.rbは下記の記事を参考に変更しました。  
[Dockerを導入後に、(Rspec)テストコードが完全に使い物にならなくなった件について②](https://qiita.com/tochisuke221/items/374359eb3cff1182ed6c)

dockerfile

[code]

    FROM ruby:2.6.3
    RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
    RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
    RUN apt-get update && apt-get install -y \
      build-essential \
      libpq-dev \
      nodejs \
      imagemagick \
      vim \
      curl \
      yarn
    
    
    WORKDIR /rspec-tutorial
    COPY Gemfile Gemfile.lock /rspec-tutorial
    RUN bundle install
    RUN yarn install
    
[/code]

docker-compose

`http://selenium_chrome:4444//wd/hub` にはwebコンテナから `curl
http://selenium_chrome:4444//wd/hub` で値が返ってきたので接続は上手くいっている気がします。

[code]

    version: '3'
    
    services:
      web:
        build: .
        # portsは -pの役割
        ports:
          - '8888:8888'
        # volumesは -vの役割
        volumes:
          - '.:/rspec-tutorial'
    
        # ttyは -itのtを意味してる
        tty: true
        # -iを意味してる
        stdin_open: true
        environment: #以下追記
          - SELENIUM_DRIVER_URL=http://selenium_chrome:4444//wd/hub
        depends_on:
          - selenium_chrome
    
      selenium_chrome:
        image: selenium/standalone-chrome-debug
        logging:
          driver: none
    
[/code]

vcr.rb

[code]

    require "vcr"
    
    VCR.configure do |config|
      config.cassette_library_dir = "#{::Rails.root}/spec/cassettes"
      config.hook_into :webmock
      config.ignore_localhost = true
      config.ignore_hosts 'chromedriver.storage.googleapis.com'
      config.configure_rspec_metadata!
    end
    
[/code]

capybara.rb

[code]

    require 'capybara/rspec'
    require 'selenium-webdriver'
    
    Capybara.register_driver :remote_chrome do |app|
      url = ENV['SELENIUM_DRIVER_URL']
      caps = ::Selenium::WebDriver::Remote::Capabilities.chrome(
        'goog:chromeOptions' => {
          'args' => [
            'no-sandbox',
            'headless',
            'disable-gpu',
            'window-size=1680,1050'
          ]
        }
      )
      Capybara::Selenium::Driver.new(app, browser: :remote, url: url, desired_capabilities: caps)
    end
    
    Capybara.javascript_driver = :selenium_chrome_headless
    
    RSpec.configure do |config|
      config.before(:each, type: :system) do
        driven_by :rack_test
      end
    
      config.before(:each, type: :system, js: true) do
        #driven_by :selenium_chrome_headless
        Capybara.server_host = IPSocket.getaddress(Socket.gethostname)
        Capybara.app_host = "http://#{Capybara.server_host}"
        driven_by :remote_chrome
      end
    end
    Capybara.default_driver = :rack_test
    Capybara.javascript_driver = :selenium_chrome_headless
    
[/code]

Gemfile

[code]

    source 'https://rubygems.org'
    
    git_source(:github) do |repo_name|
      repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
      "https://github.com/#{repo_name}.git"
    end
    
    gem 'rails', '~> 6.0.3'
    gem 'sqlite3'
    gem 'puma', '~> 4.1'
    gem 'sass-rails', '>= 6'
    gem 'uglifier', '>= 1.3.0'
    gem 'coffee-rails', '~> 4.2'
    gem 'turbolinks', '~> 5'
    gem 'jbuilder', '~> 2.7'
    
    group :development, :test do
      gem 'rspec-rails'
      gem 'factory_bot_rails', '~> 4.10.0'
      gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
    end
    
    group :development do
      gem 'web-console', '>= 3.3.0'
      gem 'listen', '>= 3.0.5', '< 3.2'
      gem 'spring'
      gem 'spring-watcher-listen', '~> 2.0.0'
      gem 'faker', require: false # for sample data in development
      gem 'spring-commands-rspec'
      gem 'rubocop-rspec'
    end
    
    group :test do
      gem 'capybara'
      gem 'selenium-webdriver'
      gem 'webdrivers', require: !ENV['SELENIUM_DRIVER_URL']
      # Or use poltergeist and PhantomJS as an alternative to Selenium/Chrome
      # gem 'poltergeist', '~> 1.15.0'
      gem 'launchy', '~> 2.4.3'
      gem 'shoulda-matchers'
      gem 'vcr'
      gem 'webmock'
    end
    
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
    
    gem 'bootstrap-sass'
    gem 'jquery-rails'
    gem 'devise'
    gem 'paperclip'
    gem 'geocoder'
    
    
[/code]

エラーの内容 `bin/rspec` の実行結果一部  
3つ出ていて上の２つもなぜそうなるか分からないのと "Message"の要素はあったので入力の部分が上手く行ってない気がします。
`VCR::Errors::UnhandledHTTPRequestError:`
ここがwebdriverの設定がうまくいってないために起きている気がします。

[code]

    Notes
    DEPRECATION WARNING: Sending mail with DeliveryJob and Parameterized::DeliveryJob is deprecated and will be removed in Rails 6.1. Please use MailDeliveryJob instead. (called from instance_exec at /usr/local/bundle/gems/activesupport-6.0.4.1/lib/active_support/callbacks.rb:428)
      user uploads an attachment (FAILED - 1)
    
    Projects
    DEPRECATION WARNING: Sending mail with DeliveryJob and Parameterized::DeliveryJob is deprecated and will be removed in Rails 6.1. Please use MailDeliveryJob instead. (called from instance_exec at /usr/local/bundle/gems/activesupport-6.0.4.1/lib/active_support/callbacks.rb:428)
      user creates a new project (FAILED - 2)
    DEPRECATION WARNING: Sending mail with DeliveryJob and Parameterized::DeliveryJob is deprecated and will be removed in Rails 6.1. Please use MailDeliveryJob instead. (called from instance_exec at /usr/local/bundle/gems/activesupport-6.0.4.1/lib/active_support/callbacks.rb:428)
    DEPRECATION WARNING: update_attributes is deprecated and will be removed from Rails 6.1 (please, use update instead) (called from complete at /rspec-tutorial/app/controllers/projects_controller.rb:67)
      user completes a project
    
    Sign in
      user signs in
    
    Sign-ups
    DEPRECATION WARNING: [Devise] `DeviseHelper#devise_error_messages!` is deprecated and will be
    removed in the next major version.
    
    Devise now uses a partial under "devise/shared/error_messages" to display
    error messages by default, and make them easier to customize. Update your
    views changing calls from:
    
        <%= devise_error_messages! %>
    
    to:
    
        <%= render "devise/shared/error_messages", resource: resource %>
    
    To start customizing how errors are displayed, you can copy the partial
    from devise to your `app/views` folder. Alternatively, you can run
    `rails g devise:views` which will copy all of them again to your app.
     (called from block in _app_views_devise_registrations_new_html_erb__4110300985041478851_70180839616580 at /rspec-tutorial/app/views/devise/registrations/new.html.erb:4)
    DEPRECATION WARNING: Sending mail with DeliveryJob and Parameterized::DeliveryJob is deprecated and will be removed in Rails 6.1. Please use MailDeliveryJob instead. (called from send_welcome_email at /rspec-tutorial/app/models/user.rb:51)
      user successfully signs up
    
    Tasks
      user toggles a task (FAILED - 3)
    
    Failures:
    
      1) Notes user uploads an attachment
         Failure/Error: fill_in "Message", with: "My book cover"
         
         Capybara::ElementNotFound:
           Unable to find visible field "Message" that is not disabled
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/finders.rb:314:in `block in synced_resolve'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/base.rb:85:in `synchronize'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/finders.rb:302:in `synced_resolve'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/finders.rb:37:in `find'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/actions.rb:92:in `fill_in'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/session.rb:792:in `block (2 levels) in <class:Session>'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/dsl.rb:50:in `block (2 levels) in <module:DSL>'
         # ./spec/system/notes_spec.rb:15:in `block (2 levels) in <top (required)>'
         # /usr/local/bundle/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'
         # -e:1:in `<main>'
    
      2) Projects user creates a new project
         Failure/Error: fill_in "Name", with: "Test Project"
         
         Capybara::ElementNotFound:
           Unable to find visible field "Name" that is not disabled
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/finders.rb:314:in `block in synced_resolve'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/base.rb:85:in `synchronize'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/finders.rb:302:in `synced_resolve'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/finders.rb:37:in `find'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/node/actions.rb:92:in `fill_in'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/session.rb:792:in `block (2 levels) in <class:Session>'
         # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/dsl.rb:50:in `block (2 levels) in <module:DSL>'
         # ./spec/system/projects_spec.rb:15:in `block (3 levels) in <top (required)>'
         # ./spec/system/projects_spec.rb:13:in `block (2 levels) in <top (required)>'
         # /usr/local/bundle/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'
         # -e:1:in `<main>'
    
      3) Tasks user toggles a task
         Got 0 failures and 2 other errors:
    
         3.1) Failure/Error: visit root_path
              
              VCR::Errors::UnhandledHTTPRequestError:
              
              
                ================================================================================
                An HTTP request has been made that VCR does not know how to handle:
                  GET http://172.23.0.3:45825/__identify__
              
                There is currently no cassette in use. There are a few ways
                you can configure VCR to handle this request:
              
                  * If you're surprised VCR is raising this error
                    and want insight about how VCR attempted to handle the request,
                    you can use the debug_logger configuration option to log more details [1].
                  * If you want VCR to record this request and play it back during future test
                    runs, you should wrap your test (or this portion of your test) in a
                    `VCR.use_cassette` block [2].
                  * If you only want VCR to handle requests made while a cassette is in use,
                    configure `allow_http_connections_when_no_cassette = true`. VCR will
                    ignore this request since it is made when there is no cassette [3].
                  * If you want VCR to ignore this request (and others like it), you can
                    set an `ignore_request` callback [4].
              
                [1] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/debug-logging
                [2] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/getting-started
                [3] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/allow-http-connections-when-no-cassette
                [4] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/ignore-request
                ================================================================================
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/request_handler.rb:97:in `on_unhandled_request'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/library_hooks/webmock.rb:129:in `on_unhandled_request'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/request_handler.rb:24:in `handle'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/library_hooks/webmock.rb:144:in `block in <module:WebMock>'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:33:in `block (2 levels) in register_global_stub'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:39:in `synchronize'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:39:in `block in register_global_stub'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/request_pattern.rb:40:in `matches?'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:73:in `block in request_stub_for'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `each'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `detect'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `request_stub_for'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:64:in `response_for_request'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:79:in `request'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/server.rb:82:in `block in responsive?'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:123:in `start_without_connect'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:150:in `start'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/server.rb:82:in `responsive?'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/server.rb:98:in `boot'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/session.rb:88:in `initialize'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara.rb:304:in `new'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara.rb:304:in `current_session'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/dsl.rb:45:in `page'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/dsl.rb:50:in `block (2 levels) in <module:DSL>'
              # ./spec/system/tasks_spec.rb:24:in `go_to_project'
              # ./spec/system/tasks_spec.rb:14:in `block (2 levels) in <top (required)>'
              # /usr/local/bundle/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'
              # -e:1:in `<main>'
    
         3.2) Failure/Error: raise VCR::Errors::UnhandledHTTPRequestError.new(vcr_request)
              
              VCR::Errors::UnhandledHTTPRequestError:
              
              
                ================================================================================
                An HTTP request has been made that VCR does not know how to handle:
                  GET http://172.23.0.3:45543/__identify__
              
                There is currently no cassette in use. There are a few ways
                you can configure VCR to handle this request:
              
                  * If you're surprised VCR is raising this error
                    and want insight about how VCR attempted to handle the request,
                    you can use the debug_logger configuration option to log more details [1].
                  * If you want VCR to record this request and play it back during future test
                    runs, you should wrap your test (or this portion of your test) in a
                    `VCR.use_cassette` block [2].
                  * If you only want VCR to handle requests made while a cassette is in use,
                    configure `allow_http_connections_when_no_cassette = true`. VCR will
                    ignore this request since it is made when there is no cassette [3].
                  * If you want VCR to ignore this request (and others like it), you can
                    set an `ignore_request` callback [4].
              
                [1] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/debug-logging
                [2] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/getting-started
                [3] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/allow-http-connections-when-no-cassette
                [4] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/ignore-request
                ================================================================================
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/request_handler.rb:97:in `on_unhandled_request'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/library_hooks/webmock.rb:129:in `on_unhandled_request'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/request_handler.rb:24:in `handle'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/library_hooks/webmock.rb:144:in `block in <module:WebMock>'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:33:in `block (2 levels) in register_global_stub'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:39:in `synchronize'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:39:in `block in register_global_stub'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/request_pattern.rb:40:in `matches?'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:73:in `block in request_stub_for'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `each'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `detect'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `request_stub_for'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:64:in `response_for_request'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:79:in `request'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/server.rb:82:in `block in responsive?'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:123:in `start_without_connect'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:150:in `start'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/server.rb:82:in `responsive?'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/server.rb:98:in `boot'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/session.rb:88:in `initialize'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara.rb:304:in `new'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara.rb:304:in `current_session'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/dsl.rb:45:in `page'
              # /usr/local/bundle/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'
              # -e:1:in `<main>'
    
    Finished in 12.52 seconds (files took 7.23 seconds to load)
    70 examples, 3 failures
    
    Failed examples:
    
    rspec ./spec/system/notes_spec.rb:11 # Notes user uploads an attachment
    rspec ./spec/system/projects_spec.rb:4 # Projects user creates a new project
    rspec ./spec/system/tasks_spec.rb:12 # Tasks user toggles a task
    
[/code]

詳しい方見て頂けないでしょうか？  
宜しくお願い致します。

### 追記

回答ありがとうございます。  
回答の通り実行してみました。

`bundle exec rspec ./spec/system/projects_spec.rb:4`
を実行したのですが、`Projects`と表示されて、そこでターミナルが停止したので `bin/rspec`
で最後まで実行しました。出力されたHTMLが下記のものなのですが、 `Name` は出力されているのでページ自体は問題ないように思えます。

[code]

    <!DOCTYPE html>
    <html>
      <head>
        <title>Projects</title>
        
    
        <link rel="stylesheet" media="all" href="/assets/application-28980a99879b3e7c5e959443ff567e1dbf870a52e9621dd48342af6b26a5b19e.css" data-turbolinks-track="reload" />
        <script src="/assets/application-72847cdf4703e06466ef126657cf2a97a72b3dfbfa563f1a3a38ba43378d6c63.js" data-turbolinks-track="reload"></script>
      </head>
    
      <body>
        <div class="container">
          <nav class="navbar navbar-default">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="/">Project Manager</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li><a href="/projects">Projects</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
              <li><a href="/users/edit">Aaron Sumner</a></li>
              <li><a rel="nofollow" data-method="delete" href="/users/sign_out">Sign Out</a></li>
          </ul>
        </div>
      </div>
    </nav>
    
          
          <h1>New Project</h1>
    
    <form action="/projects" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" />
    
      <div class="form-group">
        <label>Name</label>
        <input class="form-control" id="project_name" type="text" name="project[name]" />
      </div>...
    
[/code]

vcr.rb

下記のコードだとエラーが出力される

エラー内容

[code]

    Failure/Error:
      config.ignore_requests do |request|
        # 正規表現で http://172.23.0.3:45825 のようなURLへのリクエストをVCRの対象外とする
        request.uri.match?(/^http:\/\/(\d+\.){3}\d+:\d+/)
      end
    
    NoMethodError:
      undefined method `ignore_requests' for #<VCR::Configuration:0x0000561a4e5dddb0>
      Did you mean?  ignore_request
    
[/code]

修正前のコード

[code]

    # 以下のコードブロックを追加
    config.ignore_requests do |request|
      # 正規表現で http://172.23.0.3:45825 のようなURLへのリクエストをVCRの対象外とする
      request.uri.match?(/^http:\/\/(\d+\.){3}\d+:\d+/)
    end
    
[/code]

修正後コード

[code]

    # 以下のコードブロックを追加
      config.ignore_request do |request|
        # 正規表現で http://172.23.0.3:45825 のようなURLへのリクエストをVCRの対象外とする
        request.uri.match?(/^http:\/\/(\d+\.){3}\d+:\d+/)
      end
    
[/code]

修正後のコードが出力するエラー

[code]

    VCR::Errors::UnhandledHTTPRequestError.new(vcr_request)
              
              VCR::Errors::UnhandledHTTPRequestError:
              
              
                ================================================================================
                An HTTP request has been made that VCR does not know how to handle:
                  POST http://selenium_chrome:4444//wd/hub/session
              
                There is currently no cassette in use. There are a few ways
                you can configure VCR to handle this request:
              
                  * If you're surprised VCR is raising this error
                    and want insight about how VCR attempted to handle the request,
                    you can use the debug_logger configuration option to log more details [1].
                  * If you want VCR to record this request and play it back during future test
                    runs, you should wrap your test (or this portion of your test) in a
                    `VCR.use_cassette` block [2].
                  * If you only want VCR to handle requests made while a cassette is in use,
                    configure `allow_http_connections_when_no_cassette = true`. VCR will
                    ignore this request since it is made when there is no cassette [3].
                  * If you want VCR to ignore this request (and others like it), you can
                    set an `ignore_request` callback [4].
              
                [1] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/debug-logging
                [2] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/getting-started
                [3] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/allow-http-connections-when-no-cassette
                [4] https://www.relishapp.com/vcr/vcr/v/6-0-0/docs/configuration/ignore-request
                ================================================================================
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/request_handler.rb:97:in `on_unhandled_request'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/library_hooks/webmock.rb:129:in `on_unhandled_request'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/request_handler.rb:24:in `handle'
              # /usr/local/bundle/gems/vcr-6.0.0/lib/vcr/library_hooks/webmock.rb:144:in `block in <module:WebMock>'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:33:in `block (2 levels) in register_global_stub'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:39:in `synchronize'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:39:in `block in register_global_stub'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/request_pattern.rb:40:in `matches?'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:73:in `block in request_stub_for'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `each'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `detect'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:72:in `request_stub_for'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/stub_registry.rb:64:in `response_for_request'
              # /usr/local/bundle/gems/webmock-3.14.0/lib/webmock/http_lib_adapters/net_http.rb:79:in `request'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/remote/http/default.rb:124:in `response_for'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/remote/http/default.rb:77:in `request'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/remote/bridge.rb:588:in `execute'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/remote/bridge.rb:52:in `create_session'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/common/driver.rb:340:in `create_bridge'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/common/driver.rb:74:in `initialize'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/remote/driver.rb:44:in `initialize'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/common/driver.rb:57:in `new'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver/common/driver.rb:57:in `for'
              # /usr/local/bundle/gems/selenium-webdriver-4.0.3/lib/selenium/webdriver.rb:88:in `for'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/selenium/driver.rb:23:in `browser'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/selenium/driver.rb:118:in `save_screenshot'
              # /usr/local/bundle/gems/capybara-2.15.4/lib/capybara/session.rb:763:in `save_screenshot'
              # /usr/local/bundle/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call'
              # -e:1:in `<main>'
    
    Finished in 12.65 seconds (files took 5.04 seconds to load)
    70 examples, 3 failures
    
    Failed examples:
    
    rspec ./spec/system/notes_spec.rb:11 # Notes user uploads an attachment
    rspec ./spec/system/projects_spec.rb:4 # Projects user creates a new project
    rspec ./spec/system/tasks_spec.rb:12 # Tasks user toggles a task
    
    
    
[/code]


CC BY-SA 4.0
2021-11-18T05:37:43.533
83691
2021-11-21T01:21:06.177
2021-11-19T06:27:19.317
22565
22565
question
ruby-on-rails ruby docker rspec
Everyday Rails - RSpecによるRailsテスト入門 最初の環境構築でDockerで行ったら、seleniumを使用したテストが通らない


「Everyday Rails - RSpecによるRailsテスト入門」翻訳チームの伊藤です。本書を読んでくださってどうもありがとうございます！

質問の件ですが、ふだんDockerを使っていないので、想像で回答します。

### 1と2のエラーについて

ブラウザ上でテキスト入力ができないようですね。ただ、ログイン時のテキスト入力はうまくいってるようなので、もしかするとHTMLの出力がおかしいのかもしれません。

調査のために`save_page`メソッドを呼び出してください。

[code]

    click_link "New Project"
    save_page # この行を追加
    fill_in "Name", with: "Test Project"
    fill_in "Description", with: "Trying out Capybara"
    click_button "Create Project"
    
[/code]

それからこのテストにターゲットを絞って実行します。

[code]

    bundle exec rspec ./spec/system/projects_spec.rb:4
    
[/code]

テストが実行されると`tmp/capybara`の下に`capybara-202111190756363446470403.html`のような名前のファイルが作成されます。このHTMLを分析するとテキスト入力できない原因がわかるかもしれません。原因がわからない場合は、HTMLの出力内容を追記してください。

### 3のエラーについて

`spec/support/vcr.rb` に追加した `config.ignore_localhost = true`
で、「ローカルマシンへのアクセスはVCRの対象外とする」としているのですが、Dockerの場合は「ローカルマシン＝`localhost`」にならないのかもしれません。おそらく
`172.23.0.3:45825`
のようなIPとportを指定するんだと思いますが、この値は動的に変わりそうなので、正規表現を使って柔軟に対応できるようにした方が良さそうです。`spec/support/vcr.rb`
に次の設定を追加してみてください。

[code]

    config.ignore_localhost = true
    config.ignore_hosts 'chromedriver.storage.googleapis.com'
    
    # 以下のコードブロックを追加
    config.ignore_requests do |request|
      # 正規表現で http://172.23.0.3:45825 のようなURLへのリクエストをVCRの対象外とする
      request.uri.match?(/^http:\/\/(\d+\.){3}\d+:\d+/)
    end
    
    config.configure_rspec_metadata!
    
[/code]

それぞれ試してみたらどうなったか、結果を教えてください。よろしくお願いします。

## 追記

追記された箇所を見てみました。

### 1と2のエラーについて

以下の部分のlabelタグがおかしいですね。

[code]

      <div class="form-group">
        <label>Name</label>
        <input class="form-control" id="project_name" type="text" name="project[name]" />
      </div>
    
[/code]

ここは `<label for="project_name">Name</label>` のようにfor属性付きで出力されないと、 `fill_in
'Name'`のようにlabelのテキストで`fill_in`できません(labelのfor属性とinputのid属性を一致させる必要がある)。

ただ、ふつうに`label`ヘルパーを使えばfor属性が自動的に出力されるはずなのですが、なぜ出力されないのか謎です。

以下のサンプルコードからコードを変えたりしていませんか？

<https://github.com/everydayrails/everydayrails-
rspec-2017/blob/master/app/views/projects/_form.html.erb>

念のため、`app/views/projects/_form.html.erb` のコードと、`Gemfile.lock`の内容も見てみたいです。  
というか、今動かそうとしているコード全体をGithubにpushしてもらえるとこちらの調査が捗りそうです。

### 3のエラーについて

`An HTTP request has been made that VCR does not know how to handle: POST
http://selenium_chrome:4444//wd/hub/session`
というメッセージが見えるので、`selenium_chrome`というhostをVCRの対象外にすると良さそうです。`spec/support/vcr.rb`の`ignore_hosts`を以下のように指定してみてください。

[code]

    config.ignore_hosts 'chromedriver.storage.googleapis.com', 'selenium_chrome'
    
[/code]

## 追記・その2

コードの共有ありがとうございます。自分のマシンにもDockerをインストールして動かしてみました。  
たしかにエラーが再現したので、あれこれ試行錯誤して、最終的にテストを全部パスさせることができました。

[![screenshot](https://i.stack.imgur.com/QtwDV.png)](https://i.stack.imgur.com/QtwDV.png)

### 修正点のdiff

テストが全パスした時点の `git diff`
の結果を貼っておきます。それぞれどういう理由で変更したのかコメントを付けているので、必要に応じてwataruさんの環境で適用してみてください。

[code]

    # M1 Mac向けの設定変更なので、たぶん対応不要
    diff --git a/Dockerfile b/Dockerfile
    index 6f5034e..bb418ca 100644
    --- a/Dockerfile
    +++ b/Dockerfile
    @@ -1,5 +1,5 @@
     FROM ruby:2.6.3
    -RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
    +RUN wget --quiet -O - /tmp/pubkey.gpg  https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
     RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
     RUN apt-get update && apt-get install -y \
       build-essential \
    @@ -12,6 +12,6 @@ RUN apt-get update && apt-get install -y \
    
    
    # 末尾に / を入れないとエラーが出た
     WORKDIR /rspec-tutorial
    -COPY Gemfile Gemfile.lock /rspec-tutorial
    +COPY Gemfile Gemfile.lock /rspec-tutorial/
     RUN bundle install
    
    
    # M1 Mac用にnokogiriを再インストール + Capybaraが古くてエラーが出たので bundle update capybara を実行
    diff --git a/Gemfile.lock b/Gemfile.lock
    index 5b9f5d0..3193e9b 100644
    --- a/Gemfile.lock
    +++ b/Gemfile.lock
    @@ -68,13 +68,15 @@ GEM
           sassc (>= 2.0.0)
         builder (3.2.4)
         byebug (11.1.3)
    -    capybara (2.15.4)
    +    capybara (3.36.0)
           addressable
    +      matrix
           mini_mime (>= 0.1.3)
    -      nokogiri (>= 1.3.3)
    -      rack (>= 1.0.0)
    -      rack-test (>= 0.5.4)
    -      xpath (~> 2.0)
    +      nokogiri (~> 1.8)
    +      rack (>= 1.6.0)
    +      rack-test (>= 0.6.3)
    +      regexp_parser (>= 1.5, < 3.0)
    +      xpath (~> 3.2)
         childprocess (4.1.0)
         climate_control (0.2.0)
         coffee-rails (4.2.2)
    @@ -129,6 +131,7 @@ GEM
         mail (2.7.1)
           mini_mime (>= 0.1.1)
         marcel (1.0.2)
    +    matrix (0.4.2)
         method_source (1.0.0)
         mime-types (3.4.1)
           mime-types-data (~> 3.2015)
    @@ -137,9 +140,11 @@ GEM
           nokogiri (~> 1)
           rake
         mini_mime (1.1.2)
    +    mini_portile2 (2.6.1)
         minitest (5.14.4)
         nio4r (2.5.8)
    -    nokogiri (1.12.5-x86_64-linux)
    +    nokogiri (1.12.5)
    +      mini_portile2 (~> 2.6.1)
           racc (~> 1.4)
         orm_adapter (0.5.0)
         paperclip (6.1.0)
    @@ -289,8 +294,8 @@ GEM
         websocket-driver (0.7.5)
           websocket-extensions (>= 0.1.0)
         websocket-extensions (0.1.5)
    -    xpath (2.1.0)
    -      nokogiri (~> 1.3)
    +    xpath (3.2.0)
    +      nokogiri (~> 1.8)
         zeitwerk (2.5.1)
    
     PLATFORMS
    
    
    # Rails 6.0.4.1を使っているので、 load_defaults に6.0を指定。こうしないとlabelタグにfor属性が付かない
    diff --git a/config/application.rb b/config/application.rb
    index c6e90ab..e7d702b 100644
    --- a/config/application.rb
    +++ b/config/application.rb
    @@ -9,7 +9,7 @@ Bundler.require(*Rails.groups)
     module Projects
       class Application < Rails::Application
         # Initialize configuration defaults for originally generated Rails version.
    -    config.load_defaults 5.1
    +    config.load_defaults 6.0
    
         # Settings in config/environments/* take precedence over those specified here.
         # Application configuration should go into files in config/initializers
    
    
    # volumes の追加と変更はインストールしたgemを永続化させるため
    # SELENIUM_DRIVER_URL は / が重なっていてエラーが出たので修正
    # seleniarm/standalone-chromium はM1 Mac用のimage
    # ports の追加はこうしないと tasks_spec.rb が動かなかった
    # logging はあって困るものではないので出力するようにした
    diff --git a/docker-compose.yml b/docker-compose.yml
    index 073bc2f..e6129db 100644
    --- a/docker-compose.yml
    +++ b/docker-compose.yml
    @@ -9,17 +9,21 @@ services:
         # volumesは -vの役割
         volumes:
           - '.:/rspec-tutorial'
    +      - gem_data:/usr/local/bundle
    
         # ttyは -itのtを意味してる
         tty: true
         # -iを意味してる
         stdin_open: true
         environment: #以下追記
    -      - SELENIUM_DRIVER_URL=http://selenium_chrome:4444//wd/hub
    +      - SELENIUM_DRIVER_URL=http://selenium_chrome:4444/wd/hub
         depends_on:
           - selenium_chrome
    
       selenium_chrome:
    -    image: selenium/standalone-chrome-debug
    -    logging:
    -      driver: none
    \ No newline at end of file
    +    image: seleniarm/standalone-chromium
    +    ports:
    +      - '4444:4444'
    +
    +volumes:
    +  gem_data:
    
    
    # 変更の理由は https://blog.jnito.com/entry/2019/10/25/053521 を参照。
    diff --git a/spec/controllers/tasks_controller_spec.rb b/spec/controllers/tasks_controller_spec.rb
    index b931446..b8e6c2d 100644
    --- a/spec/controllers/tasks_controller_spec.rb
    +++ b/spec/controllers/tasks_controller_spec.rb
    @@ -8,7 +8,7 @@ RSpec.describe TasksController, type: :controller do
           sign_in user
           get :show, format: :json,
             params: { project_id: project.id, id: task.id }
    -      expect(response.content_type).to eq "application/json"
    +      expect(response.content_type).to eq "application/json; charset=utf-8"
         end
       end
    
    @@ -18,7 +18,7 @@ RSpec.describe TasksController, type: :controller do
           sign_in user
           post :create, format: :json,
             params: { project_id: project.id, task: new_task }
    -      expect(response.content_type).to eq "application/json"
    +      expect(response.content_type).to eq "application/json; charset=utf-8"
         end
    
         it "adds a new task to the project" do
    
    
    # Capybara.javascript_driver = :selenium_chrome_headless はおそらく不要なので削除
    diff --git a/spec/support/capybara.rb b/spec/support/capybara.rb
    index fbb8dfb..7040dc9 100644
    --- a/spec/support/capybara.rb
    +++ b/spec/support/capybara.rb
    @@ -16,8 +16,6 @@ Capybara.register_driver :remote_chrome do |app|
       Capybara::Selenium::Driver.new(app, browser: :remote, url: url, desired_capabilities: caps)
     end
    
    -Capybara.javascript_driver = :selenium_chrome_headless
    -
     RSpec.configure do |config|
       config.before(:each, type: :system) do
         driven_by :rack_test
    @@ -31,4 +29,3 @@ RSpec.configure do |config|
       end
     end
     Capybara.default_driver = :rack_test
    -Capybara.javascript_driver = :selenium_chrome_headless
    
    
    # 以前伝えた修正点が適用されていなかったので、適用した
    diff --git a/spec/support/vcr.rb b/spec/support/vcr.rb
    index 61088b5..1f0c627 100644
    --- a/spec/support/vcr.rb
    +++ b/spec/support/vcr.rb
    @@ -5,5 +5,9 @@ VCR.configure do |config|
       config.hook_into :webmock
       config.ignore_localhost = true
       config.ignore_hosts 'chromedriver.storage.googleapis.com', 'selenium_chrome'
    +  config.ignore_request do |request|
    +    # 正規表現で http://172.23.0.3:45825 のようなURLへのリクエストをVCRの対象外とする
    +    request.uri.match?(/^http:\/\/(\d+\.){3}\d+:\d+/)
    +  end
       config.configure_rspec_metadata!
     end
    
    
    # save_page はデバッグ用のコードなので削除
    diff --git a/spec/system/projects_spec.rb b/spec/system/projects_spec.rb
    index 1f7beb3..83194a9 100644
    --- a/spec/system/projects_spec.rb
    +++ b/spec/system/projects_spec.rb
    @@ -12,7 +12,6 @@ RSpec.describe "Projects", type: :system do
    
         expect {
           click_link "New Project"
    -      save_page
           fill_in "Name", with: "Test Project"
           fill_in "Description", with: "Trying out Capybara"
           click_button "Create Project"
    
[/code]

### その他（ひとりごと）

テストは全パスしているものの、警告は結構たくさん出ています。 `.rspec` から `--warnings`
を消せば少し減りますが、それでもまだ警告は出ています。  
<https://blog.jnito.com/entry/2019/10/15/085932>
でブログを書いたときからすでに2年が経っていて、この情報すら古くなりつつあるので、そろそろ2021年版（2022年版？）のセットアップ手順をまとめないといけないな〜と考えています。


CC BY-SA 4.0
2021-11-18T23:24:16.920
83707
2021-11-21T01:21:06.177
2021-11-21T01:21:06.177
85
85
83691
answer