Nested before_each specs

Hello all,

Does anyone know if it is possible to nest specs such that they call before_each only once for the nested describe block? The docs around testing seem a bit incomplete.

What I would like is:

describe "Page Tests" do
  before_each {
    puts "Set up some test data..."
  }

  describe "CREATE, READ, UPDATE, DELETE" do
    before_each {
      puts "START TRANSACTION..."
    }

    after_each {
      puts "ROLLBACK TRANSACTION!"
    }

    it "one" do
      true.should be_truthy
    end

    it "two" do
      true.should be_truthy
    end

    it "three" do
      true.should be_truthy
    end
  end
end

To set up the test data only once… but instead I get:

Set up some test data...
START TRANSACTION...
.ROLLBACK TRANSACTION!
Set up some test data...
START TRANSACTION...
.ROLLBACK TRANSACTION!
Set up some test data...
START TRANSACTION...
.ROLLBACK TRANSACTION!

Pretty sure you want to use before_all instead.

https://crystal-lang.org/api/master/Spec/Methods.html#before_all(&block)-instance-method

3 Likes

Wow. I swear I tried that before but was getting weird results, like it ran for every spec including those outside this file. I must have messed up the context though because it is working fine now.

Thank you and let us not speak of this again :upside_down_face: