SprocketsとWebpackerを使わずWebpackのみでassets周りを管理した話(テスト編)

前回の記事のテスト編
ponpoko-nalplus.hatenablog.com

CapybaraとChromedriverを使ったrspecを書いていく

RSpecをインストール

$ bundle exec rails generate rspec:install

RAILS_ROOT/spec/rails_helper.rb にCapybaraの設定とChromedriverの設定を追記する

require "spec_helper"
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../../config/environment", __FILE__)

abort("The Rails environment is running in production mode!") if Rails.env.production?
require "rspec/rails"

begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.include FactoryBot::Syntax::Methods

  config.after(:suite) do
    Kernel.system("rm -f #{Rails.root.join("spec", "webpack_build")}")
  end

  config.before(:each) do |example|
    if example.metadata[:type] == :system

      # type: :system 時の初回だけ yarn build:dev を走らせる
      unless  File.exist?(Rails.root.join("spec", "webpack_build"))
        Kernel.system("yarn", "build:dev")
        Kernel.system("touch #{Rails.root.join("spec", "webpack_build")}")
      end

      if example.metadata[:js]
        driven_by :selenium, using: :headless_chrome, screen_size: [1280, 800], options: {
          args: [
            "headless",
            "disable-gpu",
            "no-sandbox",
            { "lang" => "ja-JP" }
          ]
        }
      else
        driven_by :rack_test
      end
    end
  end
end

system spec を追加

require "rails_helper"
RSpec.describe "Tops", type: :system do
  describe "#index" do
    it "should render image tag", js: true do
      visit root_path
      expect(page).to have_css("img")
    end
  end
end

rails_helper.rb でwebpackのbuild:devを一回走らせることでJSのテストもできるようにはなった。
結構強引なやり方だと思うので、もうちょっとスマートなやり方を模索していきたい。