14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails6】RSpecの導入からテスト実施するまでの手順書

Last updated at Posted at 2021-02-28

はじめに

モデル、及びコントローラーごとに単体テストを実施すると、テスト実施ファイルを作成するためのコマンドを実行する必要があります。

毎回、手順を見返すのは面倒で、参考書であれば説明文等があるので、目で追うのに少し戸惑うときもあるかと思います。

そこで、テスト実施ファイル作成までの手順をまとめていれば、作業を効率化してテストを実施できるのではないかと考え、本記事を作成しました。

概要

テスト実施前の準備手順とテスト実施コマンドについて記述しております。

バージョン

rubyのバージョン ruby-2.6.5
Railsのバージョン Rails:6.0.0
rspec-rails 4.0.0

全体像

①gemの追加
②RSpecの導入

モデルの単体テストコード
③モデルのテストファイルを作成
④FactoryBotを導入し、テストを実行
⑤テストコードを実行するコマンド

コントローラーの単体テストコード
⑥コントローラーのテストファイルを作成
⑦テストコードを実行するコマンド

結合テストコード
⑧結合テストのテストファイルを作成
⑨テストコードを実行するコマンド

※インストール完了している場合は③からお進みください。

①gemの追加

Gemfileに以下の記述追加してください


group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]

# 〜省略〜

  gem 'rspec-rails', '~> 4.0.0'
  gem 'factory_bot_rails'
  gem 'faker'
end

# 〜省略〜

開発中のアプリのディレクトリに移動してから、bundle installを実行します。

$ bundle install

②RSpecの導入

RSpecをインストールします。

$ rails g rspec:install

.rspecに設定を追加します。

/.rspec
--require spec_helper
--format documentation #←追加します

③モデルのテストファイルを作成

以下のコマンドを実行して、モデルのテストファイルを生成します。

$ rails g rspec:model モデル名(単数形)

④FactoryBotを導入し、テスト実行

FactoryBotを用いてインスタンスをセットする。

その後、rspec内のモデルに、テスト内容を記述していきます。

④の補足

※初めは手動でspecディレクトリの中に、factoriesディレクトリを作成し、さらにfactoriesディレクトリの中に、FactoryBotのファイルを作成する必要があります。

しかし、その後はrails g rspec:model モデル名(単数形)実行後、自動で生成されます。

image.png

⑤テストコードを実行するコマンド

$ bundle exec rspec spec/models/モデル名_spec.rb

⑥コントローラーのテストファイルを作成

以下のコマンドを実行し、コントローラーのテストファイルを作成します。

$ rails g rspec:request コントローラー名(複数形)

⑦テストコードを実行するコマンド

$ bundle exec rspec spec/requests/コントローラー名_spec.rb

⑧結合テストのテストファイルを作成

$ rails g rspec:system オブジェクト名(複数形)

⑨テストコードを実行するコマンド

$ bundle exec rspec spec/system/オブジェクト名_spec.rb

以上です。

14
16
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
14
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?