Detect Rspec test failure on after each method

前端 未结 3 1767
既然无缘
既然无缘 2021-01-01 12:44

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         


        
相关标签:
3条回答
  • 2021-01-01 13:09

    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
    
    0 讨论(0)
  • 2021-01-01 13:19

    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 讨论(0)
  • 2021-01-01 13:28

    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
    
    0 讨论(0)
提交回复
热议问题