I am trying to learn the unit tests in Play scala, but I am running into some issues. I am trying to run several tests on my models layer like this:
"User Model" should {
"be created and retrieved by username" in {
running(FakeApplication()) {
val newUser = User(username = "weezybizzle",password = "password")
User.save(newUser)
User.findOneByUsername("weezybizzle") must beSome
}
}
"another test" in {
running(FakeApplication()) {
// more tests involving adding and removing users
}
}
}
However when doing things this way, I fail to connect to the database on the second unit test, saying that the connection is closed. I tried to solve this by enclosing all the code in a block that runs on the same fake application, but that didn’t work either.
running(FakeApplication()) {
"be created and retrieved by username" in {
val newUser = User(username = "weezybizzle",password = "password")
User.save(newUser)
User.findOneByUsername("weezybizzle") must beSome
}
"another test" in {
// more tests involving adding and removing users
}
}
The specs2 tests are performed by default in parallel which may cause problems with accessing databases, especially when you rely on the db contents provided by a previous test. So to force sequential testing you have to tell specs2 to do so:
For tests done in one
FakeApplicationyou can wrap the whole tests in it:The whole sample can be found here. That was my first attempt to deal with problems while testing MongoDB with Play! framework.
The second approach I borrowed from the salat project, which is by the way a very good source of specs examples dealing with MongoDB (although it is not a Play! framework app). You have to define a trait extending
AroundandScope, where you can put anything you need to be initialized in an application instance:Edit 2013-06-30:
In the current version of
specs2thearoundsignature should be:End of edit
Then a test can be written like that:
A full sample of such suite can be found here.
On a final note: It’s also good to clean up the test database before starting a suite: