LoginSignup
1
1

More than 3 years have passed since last update.

一意性制約を確かめるモデル単体テストコード

Posted at

はじめに

 先日の投稿の付け足しです。
ちょっと一癖あるRSpecを使ったモデルの単体テストコード 〜ユーザー登録

一意性制約を確かめるテストコード

RSpec.describe School, type: :model do
  describe '学校登録' do
    before do
      @school = FactoryBot.build(:school)
    end
  it '同じ学校名は登録できないこと' do
    @school.save #←ポイント①
    another_school = FactoryBot.build(:school) #←ポイント②
    another_school.name = @school.name #←ポイント③
    another_school.valid?
    expect(another_school.errors.full_messages).to include("学校名はすでに存在します")
  end
end

ちょこっと解説

ポイント①

FactoryBot.build(:school)を@school.saveで先に保存する。

ポイント②

anotherとして(名前は自由)別物を生成する。

ポイント③

ポイント②で新たに生成した値とポイント①で先に保存した値を同じにする。

1
1
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
1
1