今回はテストコードを書く時にRspecを導入する手順を忘備録代わりにメモします。
Gem導入
テストで使うgemを3種類導入します。
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
gem 'factory_bot_rails'
gem 'faker'
end
記述したらbundle install
して、ローカルサーバーを再起動します。
Rspecに必要なファイルをインストールする
ターミナル
% rails g rspec:install
テスト結果のログを可視化する
.rspec
--require spec_helper
--format documentation # => 追記
エラーメッセージを英語に設定(任意)
テストのエラーメッセージを英語で表示させたい場合は設定します。
RSpec.configure do |config|
の上に追記。
spec/rails_helper.rb
# 中略
I18n.locale = "en"
RSpec.configure do |config|
# 中略
FactoryBotのファイル作成
- specディレクトリの中に、
factories
ディレクトリを作成します。 - そして、その中にテスト用のFactoryBotを生成するファイルを作成する。
- 名前は
モデル名s.rb
。今回はuserモデルのテストコードを書きたいのでusers.rb
とします。
ユーザー情報をFactoryBotで生成
spec/factories/users.rb
FactoryBot.define do
factory :user do
name {Faker::Name}
email {Faker::Internet.free_email}
password = Faker::Internet.password(min_length: 6)
password {password}
password_confirmation {password}
end
end
FactoryBotが生成できていることを確認
ターミナル(コンソール)
pry(main)> FactoryBot.create(:user)
エラーが発生した時は
- 私は上記のコマンドでエラーが発生しました。その時は、Springが裏で動いていることが原因みたいなので
spring stop
コマンドでSpringを停止させます。 -
Spring stopped.
と出れば正常にSpringが停止できています。 - そして再度コンソールで
FactoryBot.create(:user)
とコマンドを打って生成を確かめましょう。
```:ターミナル`
exitでコンソール終了
% spring stop
# テストコードを記述するファイルを準備
- 下記のコマンドで`spec/models/user_spec.rb`というファイルが生成されます。
```:ターミナル
% rails g rspec:model user
テストコード記述
こんな感じでどんどんテストコードを書いていきます。
spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
pending "add some examples to (or delete) #{__FILE__}"# => 元々の記述は削除
describe 'ユーザー新規登録' do
before do
@user = FactoryBot.build(:user)
end
it "name, email, password, password_confirmationが全て入力されれば保存されること" do
expect(@user).to be_valid
end
end
end
テストコードを実行する時は
以下のコードを実行します。
ターミナル
% bundle exec rspec spec/models/user_spec.rb
Fakerの書き方について参考サイト
https://rubydoc.info/gems/faker/1.3.0/frames
http://railscasts.com/episodes/126-populating-a-database
https://github.com/takeyuweb/trygems/blob/master/try-faker/faker.md
Faker::Japanese
https://github.com/tily/ruby-faker-japanese