Rspecでモデルのテストの書き方
例えば、新しいユーザーを作るときに、メールアドレスとパスワードは確かに入力された状態じゃないとユーザーの作成を許可したくないと思ったとします。毎回毎回手動でテストをするのは面倒臭いので、コマンド一発で引き続きコードがうまく動いてるかどうかを確認しましょう。
ユーザーモデルのバリデーションは下記のようになってるとします。
/app/models/user.rb
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
it 'is not be valid without name' do
user = User.new( name: "admin@gmail.com",
email: "admin@gmail.com",
password: "admin@gmail.com",
password_confirmation: "admin@gmail.com"
)
expect(user).to be_valid # user.valid? が true になればパスする
end
end
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true