Search code examples
scalatestingspecs2

Execute code before and after specification


I have simple specification with several cases in it:

class MySpec extends Specification {

  "Something" should {

    "case 1" in {
      ...
    }

    "case 2" in {
      ...
    }
  }
}

Now I need to start application, run all cases, and shutdown the application. Starting/stopping the application is time consuming and I don't want it to happen around each case.

How do I run code before cases are started and after all the cases have finished?


Solution

  • I've come up with the following solution based on cmbaxter answer.

    import org.specs2.specification.Step
    
    trait BeforeAllAfterAll extends Specification {
      // see http://bit.ly/11I9kFM (specs2 User Guide)
      override def map(fragments: =>Fragments) = 
        Step(beforeAll) ^ fragments ^ Step(afterAll)
    
      protected def beforeAll()
      protected def afterAll()
    }
    

    Then mix BeforeAllAfterAll in Specification and implement beforeAll and afterAll methods:

    class MySpec extends Specification with BeforeAllAfterAll {
    
      def beforeAll() {
        println("Doing setup work...")
      }
    
      def afterAll() {
        println("Doing shutdown work...")
      }
    
      "Something" should {
    
        "case 1" in {
          ...
        }
    
        "case 2" in {
          ...
        }
      }
    }
    

    Finally, extract initialization to share it between specifications:

    trait InApplication extends BeforeAllAfterAll {
      def beforeAll() {
        println("Doing setup work...")
      }
    
      def afterAll() {
        println("Doing shutdown work...")
      }
    }
    
    class MySpec extends Specification with InApplication {
    
      "Something" should {
    
        "case 1" in {
          ...
        }
    
        "case 2" in {
          ...
        }
      }
    }