2
0

More than 3 years have passed since last update.

Rspec導入方法

Last updated at Posted at 2020-05-07

Railsでモデルに設定されたバリデーションの動作などをRspecを用いてテストすることが出来るので、その導入方法をまとめました。

インストール

web_console:
テスト環境で動かすと不具合が起きる可能性ありのため、development環境のみ

Gemfile

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'  #追記

...

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
terimnal
$ bundle install
Rspec設定
terminal
$ rails g rspec:install
Running via Spring preloader in process 5275
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb
spec_helper.rb

RailsなしでRspec用の共通の設定を記述するファイル。

rails_helper.rb

RailsでRspecを利用する際に、各テスト用ファイルから読み込まれる共通の設定を記述するファイル。

以下を追記する。

.rspec
--format documentation

rspecを実行し、正常に完了するメッセージが出ることを確認する。

terminal
$ bundle exec rspec
No examples found.

Finished in 0.00033 seconds (files took 0.12782 seconds to load)
0 examples, 0 failures
テスト対象

次のようにモデル設定されたバリデーションが正しく動作するか、などをテストすることができる。

app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :tweets
  has_many :comments

  validates :nickname, presence: true, length: { maximum: 6 }
end
2
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
2
0