0
0

More than 3 years have passed since last update.

Rspecの書き方

Posted at

Railsを学習していく中でRspecでのテストも書けるようになりたかったのでまとめてみます。

1 Rsepcの構造

四則演算のテストをもとに考え、Rspecの中で使用されているコードを確認します。

2 describe

describeはテストの大きな括りを表します。
なので基本的にはこのdescribeの中にテストの内容を細かく書いていきます。

describe '四則演算' do
end

3 context

contextはdescribeの中を分けたい時に使用します。
例えば四則演算でいうところの'足し算'、'引き算'、'割り算'、'掛け算'のようにdescribeの中に様々な種類があるときなどはこのcontextを使用します。

describe '四則演算' do

  context '足し算' do
  end
  context '引き算' do
  end
  context '割り算' do
  end
  context '掛け算' do
  end

end

逆に言うとdescribeの中を複数に分ける必要がなければこのcontextは必要ではありません。

4 it

itは具体的なテストの内容を記述します。
足し算なら1+1=2になるかなど具体的なテスト内容を記述します。

describe '四則演算' do

  context '足し算' do
    it '1+1=2になる' do
    end
  end
  context '引き算' do
    it '2-1=1になる' do
    end
  end
  context '割り算' do
    it '2÷2=1になる' do
    end
  end
  context '掛け算' do
    it '2x1=2になる' do
    end
  end

end

5 テストを記述する

先ほどの構造を踏まえると実際に四則演算のテストをすると以下の形になります。

describe '四則演算' do

  context '足し算' do
    it '1+1=2になる' do
    expect(1 + 1).to eq 2
    end
  end
  context '引き算' do
    it '2-1=1になる' do
    expect(2 - 1).to eq 2
    end
  end
  context '割り算' do
    it '2÷2=1になる' do
    expect(2 / 2).to eq 1
    end
  end
  context '掛け算' do
    it '2x1=2になる' do
    expect(2 * 1).to eq 2
    end
  end

end

ここで新しく出てきた
・expect
・to
・eq
について解説します。

exepect=処理内容を記述
to=期待する値が~であることを意味
eq=期待する値を記述

6 テストの実行

rspec spec/test_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