0
0

More than 3 years have passed since last update.

[rails]Rspecで単体テストを行おう!

Posted at

テストには、単体テストと統合テストの2種類がある。

-単体テスト
 1つのプログラムに対して、正常に動くかのテスト。
 (例)モデルクラスごと

-統合テスト
 1蓮の処理に関するテスト。
 (例)ユーザーの新規登録用画面から値を入力、送信して、データベースにレコードが追加されるまでの流れ

「Rspec」と「factory_bot」の導入

「Rspec」はテスト行うためのjem、
「factory_bot」はテストを行う際に一時的に情報を作成してくれる
お助けツールです。

そのため、まとめてインストールしましょう。

①jemno
インストール

Gemfile
group :development, :test do
  gem 'rspec-rails'
  gem 'factory_bot_rails'
end
ターミナル
bundle install

②RSpecの最低限必要なファイル/ディレクトリ構成をRailsにインストール

ターミナル
$ rails g rspec:install
#>      create  .rspec                  # RSpecの設定ファイル
#>      create  spec                    # スペックを格納する
#>      create  spec/spec_helper.rb     # スペック記述のためのヘルパ
#>      create  spec/rails_helper.rb    # Rails固有のスペック記述のためのヘルパ

specフォルダ.png

ここに、必要なディレクトリ・ファイルを追加していきます。

③必要なファイルの作成
ここでは、usersモデルに対してのバリデーションテストを
行なっていきます。

◆テスト用ファイル
spec/内のファイルは、app/以下のテスト対象のrbファイルに対して1
対1で対応するかたちで配置します。

app/models/user.rbに対するスペックは
spec/models/user_spec.rbとなります。

spec-file.png

◆テストのためのデータ用ファイル(factory_bot)
spec/factoriesにファクトリを配置することで、
簡単にテスト用のデータを利用できます。

factories.png

④ファイルの記述

名前空間を省略できるように設定する。

spec/rails_helper.rb
RSpec.configure do |config|
+  config.include FactoryGirl::Syntax::Methods
end
.rspec
--format documentation
--require spec_helper
spec/models/user_spec.rb

spec/factories/users.rb
FactoryBot.define do
  factory :user do
    nickname               {"taro"}
    email                  {"kkk@gmail.com"}
    password               {"00000000"}
    password_confirmation  {"00000000"}
  end
end

⑤テストの実行

ターミナル
bundle exec rspec spec/models/user_spec.rb
0
0
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
0