Rspec: around(:all) and around(:each) hook execution order

Updated . Posted . Visible to the public. Repeats.

Background

  • before(:all) runs the block once before all of the examples.
  • before(:each) runs the block once before each of your specs.

Summary

  • around(:suite) does not exist.
  • around(:all) runs after before(:all) and before after(:all).
  • around(:each) runs before before(:each) and after after(:each).

As this is not 100% obvious (and not yet documented) it is written down in this card. In RSpec 3 :each has the alias :example and :all the alias :context.

Example

RSpec.configure do |config|
  config.before(:suite) { puts 'BEFORE :suite' }
  config.after(:suite) { puts 'AFTER :suite' }
end

describe 'order of hook execution' do
  around(:all) do |each|
    puts 'AROUND BEFORE :all'
    each.run
    puts 'AROUND AFTER :all'
  end

  around(:each) do |each|
    puts 'AROUND BEFORE :each'
    each.run
    puts 'AROUND AFTER :each'
  end

  before(:all) { puts 'BEFORE :all' }
  before(:each) { puts 'BEFORE :each' }
  after(:each) { puts 'AFTER :each' }
  after(:all) { puts 'AFTER :all' }

  it { expect(true).to be(true) }
end
BEFORE :suite
 BEFORE :all
  AROUND BEFORE :all
    AROUND BEFORE :each
      BEFORE :each
        # our example runs here
      AFTER :each
    AROUND AFTER :each
  AROUND AFTER :all
 AFTER :all
AFTER :suite
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2017-08-18 11:02)