Question

specs2 has traits such as Before, After, Around, etc. in order to be able to wrap examples in setup/teardown code.

Is there anything to support setting up and tearing down testing infrastructure for each "iteration" of a ScalaCheck property, i.e. each value or set of values to be tested by ScalaCheck?

It looks like specs2's various Before, After, Around traits are designed around returning or throwing specs2 Result instances, and a Prop isn't a Result.

Was it helpful?

Solution

This is fixed now in the latest 1.12.2-SNAPSHOT. You can now write:

import org.specs2.ScalaCheck
import org.specs2.mutable.{Around, Specification}
import org.specs2.execute.Result

class TestSpec extends Specification with ScalaCheck {
  "test" >> prop { i: Int =>
    around(i must be_>(1))
  }

  val around = new Around {
    def around[T <% Result](t: =>T) = {
      ("testing a new Int").pp
      try { t }
      finally { "done".pp }
    }
  }    
}

And this will execute code before and after the "body" of the Property.

You can also go a step further and create a support method to pass in an implicit around to your Props:

class TestSpec extends Specification with ScalaCheck {
  "test" >> propAround { i: Int =>
    i must be_>(1)
  }

  // use any implicit "Around" value in scope
  def propAround[T, R](f: T => R)
                      (implicit a: Around, 
                       arb: Arbitrary[T], shrink: Shrink[T], 
                       res: R => Result): Result =
    prop((t: T) => a(f(t)))

  implicit val around = new Around {
    def around[T <% Result](t: =>T) = {
      ("testing a new Int").pp
      try { t }
      finally { "done".pp }
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top