0
2

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.

【初心者向け】RSpecによるテストの開始方法

Last updated at Posted at 2020-07-30

Rspecでテストを行うための手順をノートにまとめました。
まず、以下のGemをインストールします。

group :development, :test do
  # 省略
  gem 'rspec-rails', '~> 3.5'
  gem 'rails-controller-testing'
  gem 'factory_bot_rails'
  gem 'faker'
end

rspec-rails・・・RSpecを利用できるようにするGem
factory_bot_rails・・・簡単にダミーのインスタンスを作成することができるようにするGem
faker・・・ダミーデータを作成するGem
rails-controller-testing・・・コントローラのテストに必要なGem

bundle install します。
次に、ターミナルで以下のコマンドを入力して、RSpecを使えるようにします。

$ rails g rspec:install

すると、以下のファイルが生成されます。

 create  .rspec
 create  spec
 create  spec/spec_helper.rb
 create  spec/rails_helper.rb

この時生成されている、
rails_helper.rb
とは、RailsにおいてRSpecを利用する際に、共通の設定を書いておくファイルです。各テスト用ファイルでこちらのファイルを読み込むことで、共通の設定や、メソッドを適用します。

また、
spec_helper.rb
rails_helper.rbと同じくRSpec用の共通の設定を書いておくファイルですが、こちらはRSpecをRails無しで利用する際に利用します。

先のコマンドで生成された、.rspecを開き、下記の記述を追加します。

--require spec_helper
# 下記の記述を追加
--format documentation

これによって、テストの結果が見やすくなります。
「見やすくなる」とはどのようなことかは、こちらの記事をご参照ください。

▼RSpecには表示の出力をキレイにする --format documentation というオプションがある
https://shinkufencer.hateblo.jp/entry/2019/01/21/233000

ここまでで、RSpecを使う準備が整いました。
この時点で、ターミナルから以下のコマンドを入力すると

$bundle exec rspec

以下のように表示されて、RSpecがきちんと動いていることがわかります。

username:appname directory$ bundle exec rspec
No examples found.

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

まだ、テストを書いていないので、exampleもfailtureもないですが。

次は、userモデルについて、ごくごく簡単なテストを書いていきたいと思います。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?