开发者

Detect Rspec test failure on after each method

开发者 https://www.devze.com 2023-03-27 22:54 出处:网络
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:

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 s开发者_如何学编程ee, 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.


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消