0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

単体テストコード

Posted at

# 導入方法

① Gemfileのgroup :development, :testというグループの中にgem 'rspec-rails', '~> 4.0.0'と記入してbundle install
② % rails g rspec:installとターミナルに打ち込んでRSpecを使用できるようにする
③ .rspecに--format documentationを追記

テストコード
① specディレクトリにFactoryBotのファイルを生成
② テストする単体モデルのモデル.rbを作成
FactoryBotで指定
(例)
spec/factories/users.rb
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
FactoryBot.define do
factory :user do
name {Faker::Name.last_name}
email {Faker::Internet.free_email}
password = Faker::Internet.password(min_length: 6)
password {password}
password_confirmation {password}
end
end
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーー


ーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
require 'rails_helper'

RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end

it 'nameとemail、passwordとpassword_confirmationが存在すれば登録できること' do
  expect(@user).to be_valid
end

it 'nameが空では登録できないこと' do
  @user.name = ''
  @user.valid?
  expect(@user.errors.full_messages).to include("Name can't be blank")
end

it 'emailが空では登録できないこと' do
  @user.email = ''
  @user.valid?
  expect(@user.errors.full_messages).to include("Email can't be blank")
end

it 'passwordが空では登録できないこと' do
  @user.password = ''
  @user.valid?
  expect(@user.errors.full_messages).to include("Password can't be blank")
end

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?