LoginSignup
0
2

More than 3 years have passed since last update.

もう迷わない!RSpec導入の流れ

Posted at

RSpecとは

 Railsにおいて、単体テストコードを記述するときに用いるGemのこと。

テストコードを記述する直前までの大まかな流れ

  1. Gemfileに追記
  2. Gemをインストール
  3. rspecをインストール
  4. テストコードをターミナル上で可視化できるようにする
  5. FactoryBotとFakerのGemをGemfileに追記
  6. Gemのインストール
  7. (テスト用の画像を用意)

1. Gemfileに追記

gem 'rspec-rails'と記述する。
必ず、group :development, :test do ~ endのグループ内に

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'
end

2. Gemをインストール

ターミナルでカレントディレクトリがテストコードを使用するアプリケーションのディレクトリであることを確認の上

bundle install

3. rspecをインストール

rails g rspec:install

これによって、「specディレクトリ」や「.rspecファイル」が生成される

4. テストコードをターミナル上で可視化できるようにする

.rspec
--format documentation

を追記する。

5. FactoryBotとFakerのGemをGemfileに追記

必要に応じて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'
  gem 'factory_bot_rails'
  gem 'faker'
end

先ほどと同じgroupの中に記述。

6. Gemのインストール

bundle install

7. (テスト用の画像を用意)

public/imagesにファイル名「test_image.png」で配置。

ポイント

  • rspecは「bundle install」だけでなく、「rails g rspec:install」をして初めて使える。
  • 記述するのは、group :development, :test do ~ endのグループ内。

最後に

bundle installはRailsに取り込んだだけ!
rails g rspec:installで解凍するイメージ!

細かいテストコードはまた別の機会に。

0
2
2

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