LoginSignup
5
4

More than 1 year has passed since last update.

RSpecのbefore

Last updated at Posted at 2022-07-13

時間固定などbeforeを使う機会が多々あるのですが、引数を渡すことで実行タイミングを変更できると知らなかったのでメモです。

具体的に言うと、これまで以下のように書いていたのですが、

before do
  travel_to(Time.zone.local(2022, 7, 1, 0, 0, 0)) }
end

以下の3パターンで変更ができます。 ※afterも同様です

  1. before(:suite)
    RSpecの実行時に呼び出される。
  2. before(:all)
    context/describeブロックの実行時に呼び出される。before(:context)とも書ける。
  3. before(:each) ※デフォルト
    itの直前に毎回呼び出される。冒頭に記載したように引数を指定しないとこのパターンになる。before(:example)とも書ける。

あくまでイメージですが、コードで見るとよりわかりやすいかと思います。

RSpec.describe Sample do
  before(:all) do
    puts 'all'
  end
  before(:suite) do
    puts 'suite'
  end
  before(:each) do
    puts 'each'
  end

  describe 'sample1' do
    puts 'sample1'

    it 'do test1' do
      puts 'do test1'
    end
    it 'do test2' do
      puts 'do test2'
    end
  end

  describe 'sample2' do
    puts 'sample2'
    
    it 'do test3' do
      puts 'do test3'
    end
  end
end

# 結果
all
suite
sample1
each
do test1
each
do test2
suite
sample2
each
do test3
5
4
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
5
4