🐕

RSpec でテストに失敗したときに処理をフックする

に公開

テストが失敗したときに原因を調べるためのログを入れたかったのでやり方を調べてみた。
とりあえず after で処理をフックして example.exception があるかどうかで判定するのがシンプルに実装できそう。

# test.rb
require "rspec"

RSpec.describe "Test" do
  after do |example|
    if example.exception
      puts "!!!!!!!!!!!!!!!!!!!!!!!!!!!! テストに失敗 !!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    end
  end

  it "OK" do
    expect(false).to eq false
  end

  it "NG" do
    expect(false).to eq true
  end
end
$ rspec test.rb -fd

Test
  OK
!!!!!!!!!!!!!!!!!!!!!!!!!!!! テストに失敗 !!!!!!!!!!!!!!!!!!!!!!!!!!!!
  NG (FAILED - 1)

Failures:

  1) Test NG
     Failure/Error: expect(false).to eq true
     
       expected: true
            got: false
     
       (compared using ==)
     
       Diff:
       @@ -1 +1 @@
       -true
       +false
       
     # ./test.rb:16:in 'block (2 levels) in <top (required)>'

Finished in 0.01354 seconds (files took 0.06644 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./test.rb:15 # Test NG

after 内では letsubject など自由に参照できるのでよしなにログを仕込めます。

GitHubで編集を提案

Discussion