LoginSignup
17
17

More than 5 years have passed since last update.

Rspec初心者まとめ

Last updated at Posted at 2016-08-10

rspecで使われる色々なキーワードについて教えていただいたので、まとめてみます。

キーワード

  • describe

テストの対象となるものを書いていく。大見出しになる感じ。日本語でもOKとのこと
インスタンスメソッドは#date_range、クラスメソッドは.date_rangeとする

  • context

「〇〇の場合」というような前提条件を書く

  • before

テスト全体のデータを投入する
特定のitの中で検証するデータを作るのには使わない

  • let

変数のようなもの
itの中でデータを書き換えたりする
itブロック内では使えない

context 'hogehogeの場合' do
  it 'falseとなること' do
    let(:hogehoge) { nil } # これはできない
    expect(subject).to be false
  end
end

Failure/Error: let(:hogehoge) { nil }
       `let` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).
  • subject

オブジェクト。itの中で対象となるテストデータを定義する

  • it

「〇〇となること」というようなテスト内容を書く

実行方法

¥ rspec spec/features/hogehoge.feature
# ファイルを`:`で繋ぐと行番号で実行できる
¥ rspec spec/features/hogehoge.feature:555

書き方

  describe 'テストの大項目' do
    before do # テストを実施する前の処理      
      start_at1 = Time.new(2016, 8, 1, 9, 00, 00)
      end_at1 = Time.new(2016, 8, 31, 12, 30, 00)

      start_at2 = Time.new(2016, 8, 4, 12, 00, 00)
      end_at2 = Time.new(2016, 8, 4, 15, 00, 00)
    end
    it '期待する仕様をここに書く' do
      # 値を一致することをチェックできる
      expect(start_at1).to eq(Time.new(2016, 8, 4, 10, 30, 00))
      expect(start_at2).to eq(Time.new(2016, 8, 4, 12, 00, 00))
      expect(end_at1).to eq(Time.new(2016, 8, 4, 10, 30, 00))
      expect(end_at2).to eq(Time.new(2016, 8, 4, 12, 00, 00))
    end
  end

実際のテストコード例

# モデル(event_spec.rb)のテスト
  describe '#hogehoge?' do #インスタンスメソッド
    let(:start_at){Time.zone.local(2016, 8, 1, 9, 00, 00)} # 変数定義
    let(:end_at){Time.zone.local(2016, 8, 31, 12, 30, 00)} # 変数定義
    subject do # オブジェクト
      event = Event.new
      event.start = start_at
      event.end = end_at

      # インスタンスメソッドの戻り値がsubjectにセットされる
      event.hogehoge?(Time.zone.local(2016, 8, 4, 00, 00, 00))
    end
    context 'start_atがnilの場合' do
      let(:start_at) { nil }
      it {expect(subject).to be false} # subjectがfalseだったらOK
    end
  end
17
17
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
17
17