Rspec-core: Nested Before/Around Run In Weird Order

Created on 22 May 2018  ·  6Comments  ·  Source: rspec/rspec-core

Subject of the issue

If you have a describe block with an before(:each) and then nest a describe block with an around(:each) the around(:each) runs before the before(:each). I would have thought the around(:each) is just a nice way of writing before(:each) after(:each) and sharing some state between them. but because of the way around(:each) always runs before before(:each) even if it is nested lower it makes around(:each) much less useful.

there doesn't seem to be a test case for this behaviour in the documentation so I'm not sure if this was deliberate or not. though, i guess it would be hard to change this behaviour because probably a lot of people rely on it.

https://relishapp.com/rspec/rspec-core/v/2-0/docs/hooks/around-hooks#before/after(:each)-hooks-are-wrapped-by-the-around-hook

Your environment

  • Ruby version: 2.4.0
  • rspec-core version: 3.7

Steps to reproduce

describe "filter" do

  before(:each) do
    puts "before each outer"
  end

  describe "inner" do
    around(:each) do |example|
      puts "around each inner"
      example.run
    end

    it "should" do
      puts "example"
    end
  end

end

actual:

around each inner
before each outer
example

expected:

before each outer
around each inner
example

here is how it works if they are both before(:each) rather than using an around(:each) for the inner.

describe "filter" do

  before(:each) do
    puts "before each outer"
  end

  describe "inner" do
    before(:each) do
      puts "before each inner"
    end

    it "should" do
      puts "example"
    end
  end

end
before each outer
before each inner
example

Most helpful comment

Closing for now as there have been additional docs added, potential reorder can be looked at later.

All 6 comments

Verified this is a bit odd, we should at least document the order that we expect this to run in, I think at least around hooks should run after before when defined in an inner context

So, I think this would be a good fix for RSpec 4? It's a bit odd, indeed!

I'd like to give this a try, would you be willing to accept a PR for RSpec 4?

Yes, for RSpec 4, I would recommend developing it as in an opt-in feature, and we will eventually need a way to warn about the change in behaviour.

Sounds like a good plan to me! I'll see if I can find some time to work on it!

Closing for now as there have been additional docs added, potential reorder can be looked at later.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

take picture take  ·  5Comments

wwood picture wwood  ·  5Comments

pirj picture pirj  ·  5Comments

fimmtiu picture fimmtiu  ·  3Comments

conradwt picture conradwt  ·  3Comments