1
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 5 years have passed since last update.

[WIP]modelのRspecテストの書き方

1
Last updated at Posted at 2020-04-16

概要

私のmodelスペックの運用方針を掲載します。

サンプルコード内で<単語> で表記されている部分は
<>を抜き、単語 で指定されている内容に置き換えます。

model_specで何をテストするべきか?

  • バリデーション
  • クラスメソッド
  • インスタンスメソッド

サンプルコード(テンプレート)

app/spec/models/xxxx_spec.rb
require 'rails_helper'

RSpec.describe モデル名, type: :model do
  before do
    インスタンス変数の準備
  end
  
  # <バリデーションのテスト>
  describe "<カラムの名前が>" do
    before do
      インスタンス変数の準備
    end
    context "<有効な条件ならば>" do
      it "<有効な状態である>" do
        expect<>
      end
    end
    context "<無効な条件ならば>" do
      it "<無効な状態である>" do
        expect<>
      end
    end
  end

  # <メソッドのテスト>
  describe "<メソッドの機能が>" do
    before do
      インスタンス変数の準備
    end
    context "<条件1ならば>" do
      it "<求める結果1である>" do
        expect<>
      end
    end
    context "<条件2ならば>" do
      it "<求める結果2である>" do
        expect<>
      end
    end
  end
  
end

00_テストレシピについて

共通利用することの多いテスト内容はspec/custom_helper.rbファイルを作成し、その中でメソッド化して記述します。'rails_helper'の中でrequire しておくことで、各specファイル内で、メソッドを利用します。

01_バリデーションのテストレシピ

独自のバリデーションを設定している部分、権限周り、決済周りは、優先的にテストをかきます。
modelファイルに単純な設定をするだけで実装できるバリデーションはテスト化の優先度下げます。

必須入力

任意入力

指定文字数

指定文字種類

02_クラスメソッドのテストレシピ

03_インスタンスメソッドのテストレシピ

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