はじめにrspec-rails
、factory_bot_rails
、faker
を導入する
# Gemfile group :development, :test do gem 'rspec-rails' gem 'factory_bot_rails' gem 'faker' end
ターミナル$ bundle install
、rails g rspec install
を行う。作成された.rspecファイルに--format documentation
(表示の出力がきれいになるようにフォーマットを指示する)を記述
--format option Use the --format option to tell RSpec how to format the output.
RSpec ships with a few formatters built in. By default, it uses the progress formatter, which generates output like this:
仕様に沿ったユーザーモデルのデータを設定する
重複したemailは登録できないことにしているため、uniqueを付けて一意となるようにする
# spec/factories/users.rb FactoryBot.define do factory :user do email { Faker::Internet.unique.free_email } password { '123456' } password_confirmation { password } end end
factory_botを使う
インスタンス編集@userに、先程設定したuserのデータを入れる
# spec/models/user_spec.rb RSpec.describe User, type: :model do describe '#create' do before do @user = FactoryBot.build(:user) end end end
createアクションをテストする。テスト項目を書き出す
# spec/models/user_spec.rb RSpec.describe User, type: :model do describe '#create' do before do @user = FactoryBot.build(:user) end it 'email, password, password_confirmationが存在すれば登録できること' do end it 'emailが空では登録できないこと' do end it '重複したemailが存在する場合登録できないこと' do end it 'emailには@が含まれてなければ登録できないこと' do end it 'passwordが空では登録できないこと' do end it 'passwordが6文字以上であれば登録できること' do end it 'passwordが5文字以下では登録できないこと' do end it 'password_confirmationが必須であること' do end end end
洗い出した項目を検証するためのコードを書く
RSpec.describe User, type: :model do describe '#create' do before do @user = FactoryBot.build(:user) end it 'emailが空では登録できないこと' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include("Email can't be blank") end it '重複したemailが存在する場合は登録できないこと' do @user.save another_user = FactoryBot.build(:user) another_user.email = @user.email another_user.valid? expect(another_user.errors.full_messages).to include('Email has already been taken') end it 'emailに@が含まれていなければ登録できないこと' do @user.email = 'sample.com' @user.valid? expect(@user.errors.full_messages).to include('Email is invalid') end it 'passwordが空では登録できないこと' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it 'passwordが6文字以上であれば登録できること' do @user.password = "123456" expect(@user).to be_valid end it 'passwordが5文字以下では登録できないこと' do @user.password = '12345' @user.password_confirmation = '12345' @user.valid? expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)') end it 'password_confirmationが空では登録できないこと' do @user.password_confirmation = '' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end end end
テストコードを実行する
# spec/models/user_spec.rbの実行 $ bundle exec rspec spec/models/user_spec.rb