Detect Rspec test failure on after each method
Asked Answered
C

3

24

I am trying to run an RSpec test, and I want to detect if the test failed in the after method. I have something like this right now:

after(:each) do
  cc = ConnectController.new()
  cc.update(<TEST-SERVER-CONTROLLER>, <TC-RESULT-ID>, result?)    
end

As you can see, the result? function is what I need to replace, to detect if the test fails or not, and to also get information about the test that failed.

Conjoint answered 11/8, 2011 at 13:27 Comment(0)
C
25

In addition to Daniel's answer, in Rspec3 the example method was deleted (see here for more info).

You will have to do something like this:

after(:each) do |example|
  if example.exception
    # ...
  end
end
Collum answered 2/10, 2014 at 15:31 Comment(0)
B
15

EDIT: this answer is only valid for RSpec 2. for RSpec 3 see geekazoid's answer.

The after each block runs in the context of class which exposes example and you can detect failures by checking the exception method on example thusly:

after(:each) do
  if example.exception != nil
    # Failure only code goes here
  end
end
Berne answered 11/6, 2012 at 18:46 Comment(0)
N
1

I was looking for how to check if success for all examples in a group in a after(:context) / after(:all) block. Here's what I came up with:

after(:all) do |example_group|
  all_groups = example_group.class.descendants
  failed_examples = all_groups.map(&:examples).flatten.select(&:exception)

  if failed_examples.empty?
    # runs only if there are no failures
    do('something')
  end
end
Norval answered 28/11, 2017 at 4:45 Comment(1)
Thanks. All the other answers were focused on after(:each) which adds to the runtime. It's really useful to be able to check once after the whole suite.Uncounted

© 2022 - 2024 — McMap. All rights reserved.