I implemented specs2 specification that looks something like this:
class MySpec extends Specification {
"My database query" should {
"return some results " in {
val conn = createJdbcConn()
try {
// matcher here...
} finally {
conn.close()
}
}
}
This ugly boilerplate is repeated in all my test cases. I have to open (and then close) a new connection for each in
.
What is the idiomatic way in Specs2 close resources such as in this case - perhaps using the After
(or BeforeAfter
) trait to properly close the connection?
Another option is to use the FixtureExample
trait introduced in 2.0, to avoid using a variable:
import org.specs2._
import specification._
import execute._
trait DbFixture extends FixtureExample[JdbcConnection] {
// type alias for more concise code
type DBC = JdbcConnection
/**
* open the connection, call the code, close the connection
*/
def fixture[R : AsResult](f: JdbcConnection => R): Result = {
val connection = createJdbcConnection
try AsResult(f(connection))
finally connection.close
}
}
class MySpec extends Specification with DbFixture {
"My database query" should {
"return some results" in { connection: DBC =>
// do something with the connection
success
}
}
}