Search code examples
scalaspecs2

Execute a before/after each in a specified should block out of many in Specs2


I have a spec like the following written:

class MySpec extends Specification {

  "A" should {
    "be true" in {
      true must beEqualTo(true)
    }
  }

  "B" should {
    "be false" in {
      false must beEqualTo(false)
    } 
  }
  ...
}

How do I/Can I specify a before/after statement to execute only within the "B" block (for instance) for each test.


Solution

  • You can create a context for your test:

    trait Context extends BeforeAfter {
      def before: Any = println("Doing setup")
      def after: Any = println("Done. Cleanup")
    }
    
    "B" should {
      "be false" in new Context  {
        false must beEqualTo(false)
       }
    }
    

    You can have a look at this link if you need to do some tricky things with specs2.