モデルのテストについて
まず既存のモデルに対してモデルスペックを作る。
それからモデルのバリデーション、クラスメソッド、インスタンスメソッドのテストを書く。テストを作りながらスペックの整理する。
■アウトラインを決める。
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
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