Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

RSpec | rspec command | テスト順のランダム化

概要

rspec command | テスト順のランダム化

詳細

rspec command実行時に、spec_helperに

config.order = 'random'

の設定を行うことで各テストケースをランダムな順序で実行します。
この設定を行った場合、テスト実行終了時に乱数の種(seed)が表示されます。
同じ乱数によるテスト順を再現したい場合は、

rspec -fd --order rand:xxxx

※xxxxはseedの値

のようにすると再現できます。
ランダムなテストにすることで、テスト順序に依存したケースを発見することができます。

構成

$ tree
┣ lib
| ┗ hoge.rb
┗ spec
    ┣ hoge_spec.rb
    ┗ spec_helper.rb

hoge.rb

# encoding: utf-8

class Hoge
  5.times do |i|
    define_method "hoge#{i}".to_sym do
      "hoge#{i}"
    end
  end
end

hoge_spec.rb

require 'spec_helper'
require 'hoge'

describe Hoge do
  5.times do |i|
    it "hoge#{i}" do
      expect(Hoge.new.send "hoge#{i}".to_sym).to eq("hoge#{i}")
    end
  end
end

テストを2回実行してみる

テスト順がランダムになっていることがわかります。

$ rspec -fd
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}

Hoge
  hoge3
  hoge1
  hoge4
  hoge2
  hoge0

Finished in 0.002 seconds
5 examples, 0 failures

Randomized with seed 33029

$ rspec -fd
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}

Hoge
  hoge0
  hoge3
  hoge4
  hoge2
  hoge1

Finished in 0.003 seconds
5 examples, 0 failures

Randomized with seed 33620

先ほど一回目に実行したテストを再現させてみる

seed 33029のケースを再現させます。

$ rspec -fd --order rand:33029
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}

Hoge
  hoge3
  hoge1
  hoge4
  hoge2
  hoge0

Finished in 0.002 seconds
5 examples, 0 failures

Randomized with seed 33029