12
9

【Rails】rubocop導入手順の備忘録

Last updated at Posted at 2023-09-26

はじめに

お疲れさまです。
おおくまです。

現在、色々なことを試して遊んでいるミニアプリに重い腰を上げてrubocopを導入しました。
その際の備忘録です。

環境

Ruby 3.2.2
Rails 7.0.8

注意点

私はプログラミング学習中で、初学者です。
内容に誤りがある場合があります。
コメント等で教えていただけると幸甚です。

実装

rubocopをインストールする。

Gemfile
+ gem 'rubocop', require: false

bundle installを実行。

bundle exec rubocopでrubocopを通してみる。

ターミナル
52 files inspected, 688 offenses detected, 669 offenses autocorrectable

The following RuboCop extension libraries are installed but not loaded in config:
  * rubocop-capybara
  * rubocop-rails

恐ろしい数の指摘と、2つのライブラリをインストールするように提案が返ってきました。

rubocop-capybararubocop-railsをインストールする。

Gemfile
+ gem 'rubocop-capybara', require: false
+ gem 'rubocop-rails', require: false

bundle installを実行。

rubocop --auto-gen-configを実行。
.rubocop.ymlファイルが作られる。

ターミナル
Please also note that you can opt-in to new cops by default by adding this to your config:
  AllCops:
    NewCops: enable

また、こういった提案があったので、.rubocop.ymlファイルに書き込む。

.rubocop.yml
AllCops:
  NewCops: enable
  Exclude:
    - 'bin/**/*'
    - 'db/migrate/**/*'
    - 'db/schema.rb'
    - 'vendor/**/*'

require:
  - rubocop-rails
  - rubocop-capybara

Exclude下にはチェック不要のファイルを記入する。

再度、bundle exec rubocopを実行してみる。

ターミナル
47 files inspected, 651 offenses detected, 632 offenses autocorrectable

651個の指摘のうち、632個は自動修正可能であるとのことなので、
bundle exec rubocop -aを実行し、残りは手作業で直します。

再度、bundle exec rubocopを実行してみる。

ターミナル
Inspecting 37 files
.....................................

37 files inspected, no offenses detected

全てチェックが通りました。
最後まで読んでいただきありがとうございました。

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9