When I first started writing DAO tests in Scala/Slick with PostgreSQL I would use a trait to create a new database for each individual test. I kept track of them in a list and dropped them in an
afterAll() method. This worked well, except I found it too slow for more than a trivial number of tests. This post shows my current much faster approach.
I’m currently using a trait that creates a new database for each spec—named after the test class so multiple tests can run simultaneously—and drops this database after the tests have run. Here it is (import & package lines omitted for brevity):
The above trait doesn’t mandate any particular testing style. (I’ve used
FlatSpec in the below example, but you can use any of the other styles ScalaTest supports.) In your test class you have to use the
BeforeAndAfter trait to create & drop the schema before and after each test. Here’s an example:
I would have preferred to run each test in a transaction and roll back afterwards, but I couldn’t figure out how to make Slick do that. So I went for the next best thing and dropped & re-created the tables for each test.