typelevel / doobie

Functional JDBC layer for Scala.
MIT License
2.17k stars 359 forks source link

Example of test with in-memory database table creation #253

Open trepidacious opened 8 years ago

trepidacious commented 8 years ago

It would be handy to be able to write tests against an in-memory database, so that testing does not rely on an existing database. An example of this using setup/teardown in a specs2 test would be very useful.

tpolecat commented 8 years ago

:+1:

trepidacious commented 8 years ago

I'm not sure whether this is the best way of doing things, but I got something apparently working with specs2 :)

The key thing seems to be to use a should and in format for the test, rather than having the checks in the body of the Specification as in the current book of doobie example (Queries.create creates the tables, and the other queries use them). I also tried using a step{ DAO.create... } at the start of the specification but this doesn't seem to work:

import doobie.contrib.specs2.analysisspec.AnalysisSpec
import doobie.imports._
import org.specs2.mutable.Specification
import scalaz.concurrent.Task

object QueriesTestSpec extends Specification with AnalysisSpec {

  val transactor = DriverManagerTransactor[Task]("org.h2.Driver", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "")

  "Queries" should {
    "pass checks" in {

      check(Queries.create)

      DAO.create.transact(transactor).run

      check(Queries.insertUser("A", "User", "user@domain.com"))
      check(Queries.userById(1))
    }
  }
}