Everyday Rails - RSpecによるRailsテスト入門 まとめ

モデルのテストについて

 

まず既存のモデルに対してモデルスペックを作る。

それからモデルのバリデーション、クラスメソッド、インスタンスメソッドのテストを書く。テストを作りながらスペックの整理する。

 

■アウトラインを決める。

require 'rails_helper'

RSpec.describe User, type: :model do
  # 姓、名、メール、パスワードがあれば有効な状態であること
  it "is valid with a first name, last name, email, and password"
  # 名がなければ無効な状態であること
  it "is invalid without a first name" 
  # 姓がなければ無効な状態であること
  it "is invalid without a last name" 
  # メールアドレスがなければ無効な状態であること
  it "is invalid without an email address"
  # 重複したメールアドレスなら無効な状態であること
  it "is invalid with a duplicate email address"
  # ユーザーのフルネームを文字列として返すこと
  it "returns a user's full name as a string"
end

 

■具体的なテストコードを書いていく。

# 姓、名、メール、パスワードがあれば有効な状態であること
it "is valid with a first name, last name, email, and password" do
  user = User.new(
    first_name: "Aaron",
    last_name: "Sumner",
    email: "test@exaple.com",
    password: "test-password"
  )
  expect(user).to be_valid
end

# 名がなければ無効な状態であること
it "is invalid without a first name" do
  user = User.new(first_name: nil)
  user.valid?
  expect(user.errors[:first_name]).to include("can't be blank")
end

# rails tutorialではエラーメッセージまではチェックしていない
it "is invalid without a first name(rails tutorial ver.)" do
  user = User.new(first_name: nil)
  expect(user).to_not be_valid
end

 

まとめ

 ーexample(itで始まる1行)一つにつき、結果を一つだけ書く。

first_name、last_name、emailのバリデーションをそれぞれ分けてテストすることにより、exampleが失敗したときに問題が起きたバリデーションを特定できる。

起きてほしいことと、起きてほしくないことをテストすること。

 

toをnot to  にすること

コードを変更する等がある。

 

 ーexampleを書くときは両方のパスを書くことが必要となる。

境界値テストをすること。

 

 ―バリデーションが4文字以上10文字以下なら、4文字と10文字、そして3文字と11文字もテストすること。

 

 ーdescribe、context、before、afterを使ってスペックをDRYにできる。

 

参考に

https://qiita.com/jnchito/items/42193d066bd61c740612