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.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Leo
  • 421
  • 4
  • 5

3 Answers3

24

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
finiteautomata
  • 3,753
  • 4
  • 31
  • 41
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
Daniel Evans
  • 6,788
  • 1
  • 31
  • 39
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
user2490003
  • 10,706
  • 17
  • 79
  • 155
austinheiman
  • 939
  • 1
  • 12
  • 17
  • 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. – user2490003 Jan 30 '19 at 16:12