目次

Railsのインストールまで

rbenvのインストール

# rbenvへのPATHを通す
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc

# rbenvを使うために必要な「rbenv init -」コマンドを設定
$ echo 'eval "$(rbenv init -)"' >> ~/.zshrc

# rbenvのインストール
$ brew install rbenv ruby-build

Rubyのインストール

# インストールできるバージョンを確認
$ rbenv install --list

# バージョンを指定してインストール
$ rbenv install x.y.z

Rubyのバージョンを適用

# 作業ディレクトリへ移動
$ cd ${DIR}

# 現在のディレクトリ下にRuby x.y.zを適用
$ rbenv local x.y.z

# 反映
$ rbenv rehash

bundlerのインストール

# bundlerがインストールされているか確認
$ gem list | grep bundler

# バージョンを指定してインストール
$ gem install bundler -v 1.17.3

Railsのインストール

# インストール可能なrailsのバージョンを確認
$ gem search '^rails$' --all

# バージョンを指定してインストール
$ gem install rails -v 6.0.3

Railsアプリの生成とサーバー立ち上げまで

Railsアプリ作成

  • Railsのバージョンを指定 (_6.0.3_)
  • デフォルトのデータベースを指定 (-d mysql)
    • PostgreSQLの場合は-d postgresql
  • gemのインストールはスキップ (--skip-bundle)
$ rails _6.0.3 new ${PROJECT_NAME} -d mysql --skip-bundle

Gemfileを編集

Gemfileの例

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '6.0.3'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.3.18', '< 0.5'
# Use Puma as the app server
gem 'puma', '4.3.4'
# Use SCSS for stylesheets
gem 'sass-rails', '5.1.0'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '4.0.7'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '5.2.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '2.9.1'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '1.4.5', require: false
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use bulk insert in ActiveRecord
# gem 'activerecord-import'
# Use serializer for generating JSON
# gem 'active_model_serializers'
# Use devise for authentication
# gem 'devise'
# gem 'devise-i18n'
# For environment variables
# gem 'dotenv-rails'
# Enumerated attributes with I18n
# gem 'enumerize'
# For HTTP client
# gem 'faraday'
# Use HAML template engine
gem 'haml-rails'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# For asynchronous processing (Redis backed for creating background jobs)
# gem 'resque'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', '11.0.1', platforms: [:mri, :mingw, :x64_mingw]
  # Generate dummy data
  gem 'faker'
  # Run test automatically
  gem 'guard-rspec', require: false
  # Use pry for better console and debug
  gem 'pry-byebug'
  gem 'pry-doc'
  gem 'pry-rails'
end

group :development do
  # Listen file modification
  gem 'listen', '3.1.5'
  # Static code analyzer
  gem 'rubocop', require: false
  gem 'rubocop-rails', require: false
  gem 'rubocop-rspec', require: false
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring', '2.1.0'
  gem 'spring-commands-rspec'
  gem 'spring-commands-rubocop'
  gem 'spring-watcher-listen', '2.0.1'
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '4.0.1'
end

group :test do
  # For integration test by simulating
  gem 'capybara', '3.28.0'
  # Browser simulate
  gem 'selenium-webdriver', '3.142.4'
  # Clean database for testing
  gem 'database_cleaner'
  # Generate test data (model instance)
  gem 'factory_bot_rails'
  # For 'assigns' and 'assert_template'
  gem 'rails-controller-testing'
  # Test tool
  gem 'rspec-rails'
  # For code coverage
  gem 'simplecov', require: false
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers', '4.1.2'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

各種Gemをインストール

$ bundle install

サーバー立ち上げ

# railsのバージョンを確認
$ rails -v

# サーバー起動
$ rails s

.gitignoreの例

# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
#   git config --global core.excludesfile '~/.gitignore_global'

# Ignore bundler config.
/.bundle
/vendor/bundle

# Ignore the default SQLite database.
/db/*.sqlite3
/db/*.sqlite3-journal
/db/*.sqlite3-*

# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

# Ignore pidfiles, but keep the directory.
/tmp/pids/*
!/tmp/pids/
!/tmp/pids/.keep

# Ignore uploaded files in development.
/storage/*
!/storage/.keep

/public/assets
.byebug_history

# Ignore master key for decrypting credentials and more.
/config/master.key

/public/packs
/public/packs-test
/node_modules
/yarn-error.log
yarn-debug.log*
.yarn-integrity

.env

# Editor
.idea
*.iml
.vscode

その他主要なGemの設定

Spring (spring), spring-commands-rspec, spring-commands-rubocop

アプリケーションをバックグラウンドで実行したままにしておくことにより、railsrspecコマンドの2回目以降の起動を早くする
bin/spring, bin/rspecを生成するため、またbin/rails, bin/rakeをSpring対応に変換するために、以下のコマンドを実行

$ bundle exec spring binstub --all

Springの使い方

bin/xxxコマンド実行の2回目以降は、自動的にSpringが起動されてRailsアプリケーションがバックグラウンドで動いている状態となる

  • Springが起動しているかどうかの状態を確認する
    $ bin/spring status
    
  • 起動しているSpringを停止する
    $ bin/spring stop
    

bundle exec xxxbin/xxxの違いについて

[Qiita] Rails 4.1以降のコンソールコマンドは必ず bin/ を付けなきゃいけないの?
↑の記事に詳しく書かれている
Spring対応のコマンドを実行する場合はbin/xxxを使う
(railsコマンドの場合はbin/をつけなくても、プロジェクトルートのbinディレクトリにあるrails実行ファイルを優先的に起動する仕様となっているため、bin/railsがSpringを使うようになっていればbin/をつけなくてもSpringが起動することになる)

RuboCop (rubocop), rubocop-rails, rubocop-rspec

静的コード解析ツール

設定ファイル.rubocop.ymlの例

inherit_from:
  - .rubocop_todo.yml

require:
  - rubocop-rails
  - rubocop-rspec

AllCops:
  DisplayCopNames: true
  TargetRubyVersion: 2.6
  Exclude:
    - 'db/schema.rb'
    - 'vendor/**/*'
    - 'bin/**/*'
    - 'node_modules/**/*'

Rails:
  Enabled: true

################## Layout ##################

Layout/LineLength:
  Max: 160
  Exclude:
    - 'spec/**/*'

Layout/EmptyLinesAroundAttributeAccessor:
  Enabled: true

Layout/SpaceAroundMethodCallOperator:
  Enabled: true

Lint/DeprecatedOpenSSLConstant:
  Enabled: true

Lint/RaiseException:
  Enabled: true

Lint/StructNewOverride:
  Enabled: true

################## Metrics ##################

Metrics/MethodLength:
  Max: 20

################## Naming ##################

# メソッド名のprefixに「set_」「get_」を許可
Naming/AccessorMethodName:
  Enabled: false

################## Style ##################

# 複数行での「lambda」で「->」による省略記法を許可
Style/Lambda:
  Enabled: false

# モジュール名::クラス名の定義を許可
Style/ClassAndModuleChildren:
  Enabled: false

# 「and」「or」の使用を許可
Style/AndOr:
  Enabled: false

# ドキュメントのないclassやmoduleを許可
Style/Documentation:
  Enabled: false

# 日本語でのコメントを許可
Style/AsciiComments:
  Enabled: false

Style/ExponentialNotation:
  Enabled: true

Style/HashEachMethods:
  Enabled: true

Style/HashTransformKeys:
  Enabled: true

Style/HashTransformValues:
  Enabled: true

Style/SlicingWithRange:
  Enabled: true

$ rubocopコマンドを実行すると警告が出るはず

RuboCopの警告修正の流れ

  1. $ rubocop --auto-gen-configを実行し、全ての警告を一旦.rubocop_todo.ymlに退避にす
  2. .rubocop_todo.yml内の警告の中から一番上の警告をコメントアウトする
  3. $ rubocopを実行
    • → 警告を修正する or 警告されたくないルールの場合は.rubocop.ymlを編集
  4. 修正等して警告が出なくなったら、.rubocop_todo.ymlのコメントアウトした部分を削除する
  5. .rubocop_todo.yml内の全ての警告を修正し終わるまで2.5.を繰り返す

RSpec (rspec-rails), factory_bot_rails

RSpec: Rubyコードをテストするためのテストツール
factory_bot: テストデータ作成時に使用

RSpecの設定ファイル群を生成

rails g rspec:install

config/application.rbを編集して、必要なテストファイルのみ生成されるようにする

application.rbの例

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module SampleApp
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
    config.generators do |g|
      g.assets false
      g.test_framework :rspec,
                       view_specs: false,
                       helper_specs: false,
                       routing_specs: false,
                       controller_specs: true,
                       request_specs: false,
                       fixtures: true
      g.fixture_replacement :factory_bot, dir: 'spec/factories'
    end
  end
end

RSpecを実行できるか確認

$ bin/rspec

spec/rails_helper.rbの設定

  • spec/support/下のファイルを読み込むために以下の1文のコメントアウトを外す
    Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
    
  • factory_botのメソッド(FactoryBot.create等)を使用する際にクラス名の指定(FactoryBot.xxx)を省略するために以下のように編集
    RSpec.configure do |config|
      ...
    
      config.include FactoryBot::Syntax::Methods
    end
    

factory_botのデータ定義

factory_botのデータ(factory)の定義はspec/factories/xxx.rbに記述 (デフォルトで読み込んでくれる)

DatabaseCleaner (database_cleaner)

テストの際などデータベースを綺麗にする戦略を指定できる
ex) RSpec実行前にtruncate tableでレコードを消し、DBを綺麗にする手段はtransactionをはってrollbackする
(RSpecのデフォルトではbefore(:each)でtransactionを張ってafter(:each)でrollback)

spec/rails_helper.rbでの設定例

RSpec.configure do |config|
  ...

  # RSpecの実行前に一度、実行
  config.before(:suite) do
    # DBを綺麗にする手段を指定、トランザクションを張ってrollbackするように指定
    DatabaseCleaner.strategy = :transaction
    # truncate table文を実行し、レコードを消す
    DatabaseCleaner.clean_with(:truncation)
  end

  # exampleが始まるごとに実行
  config.before(:each) do
    # strategyがtransactionなので、トランザクションを張る
    DatabaseCleaner.start
  end

  # exampleが終わるごとに実行
  config.after(:each) do
    # strategyがtransactionなので、rollbackする
    DatabaseCleaner.clean
  end
end

詳細記事

[Qiita] DatabaseCleanerの実装と使い所

Haml (haml-rails)

Haml: HTMLを簡潔に書けるマークアップ言語

既存のERB(application.html.erb等)をHamlに変換する

$ rails haml:erb2haml