Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Rspec test failure on after each method

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.

like image 467
Leo Avatar asked Aug 11 '11 13:08

Leo


3 Answers

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
like image 115
finiteautomata Avatar answered Oct 19 '22 18:10

finiteautomata


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
like image 21
Daniel Evans Avatar answered Oct 19 '22 18:10

Daniel Evans


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
like image 1
austinheiman Avatar answered Oct 19 '22 19:10

austinheiman