Scalatest run code before and after specific test

scala, scalatest

Solution

You can do this (or a variation of this):

def beforeAfter[T](before: =>Unit, after: =>Unit)(t: =>T) = {
  before
  try t
  finally after
}

Then

beforeAfter(before = action1, after = action2) {
  test
}

Problem

I want to ask a quick question. Is there a way to run some code before and after a specific test? Imagine for a moment that I want some environment-setup code to be executed before and after a specific test, but not in all tests. I've tried to define a function to do that for me and just call that function ant the beginning and the end of my test. It works fine but if the test fails, the function I call at the end isn't called (since the test failed). Is there a way to restrict the beforeAndAfter trait to be executed only at specific tests? Thanks.

Original source