LoginSignup
2
3

More than 5 years have passed since last update.

Railsでよく利用するコマンドとRSpec、FactoryBotを導入するまで【Railsチートシート】

Last updated at Posted at 2018-11-10

Railsで新規アプリを作成する時、毎回調べてしまうためまとめる。

今回のリポジトリのURL: https://github.com/harhogefoo/rails_rspec

前提環境

  • ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]
  • Rails5.1.6

新規アプリ作成

今回はアプリ名をrails_rspecとして記述します。

$ rails new rails_rspec
# APIを作成する場合は
$ rails new rails_rspec --api

$ cd rails_rspec

RSpecをインストールする

公式: https://github.com/rspec/rspec-rails

GemfileにRSpecを追加

Gemfile
group :development, :test do
  gem 'rspec-rails'
end

RSpecの設定

$ bundle install
$ bin/rails g rspec:install

.rspecを編集する

.rspec
--require spec_helper
--format documentation

binstubを利用する

  • 高速にRSpecの実行が可能になる
Gemfile
group :development do
  gem 'spring-commands-rspec'
end
$ bundle install
$ bundle exec spring binstub rspec
* bin/rspec: generated with spring

bin配下に rspec が生成される。

不要なspecファイルを生成しないようにする

config/application.rb
module RailsSpec
  class Application < Rails::Application

  ...
    config.generators do |g|
      g.test_framework(
        :rspec,
        view_specs: false,
        helper_specs: false,
        routing_specs: false,
        request_specs: false
      )
    end
  end

RSpecを実行する

$ bin/rspec
c
Running via Spring preloader in process 32839
No examples found.

Finished in 0.00042 seconds (files took 0.24181 seconds to load)
0 examples, 0 failures

FactoryBotをインストールする

Gemfile
group :development, :test do
  ...
  gem 'factory_bot_rails'
end
$ bundle install

ファクトリーの作成

$ bin/rails g factory_bot:model User

モデルの作成

  • モデル名は単数形で書くこと
$ bin/rails g model user

コントローラーの作成

  • コントローラー名は対象のモデル名の複数形にすること
$ bin/rails g controller users

specファイルの作成

モデルのspecファイルの作成

$ bin/rails g rspec:model user

コントローラーのspecファイルの作成

$ bin/rails g rspec:controller users
2
3
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
2
3