Arve
Arve

Reputation: 8128

How do I insert test data in Play Framework 2.0 (Scala)?

I'm having some problems with making my tests insert fake data in my database. I've tried a few approaches, without luck. It seems that Global.onStart is not run when running tests within a FakeApplication, although I think I read that it should work.

object TestGlobal extends GlobalSettings {
  val config = Map("global" -> "controllers.TestGlobal")

  override def onStart(app: play.api.Application) = {
    // load the data ... 
  }
}

And in my test code:

private def fakeApp = FakeApplication(additionalConfiguration = (
  inMemoryDatabase().toSeq +
  TestGlobal.config.toSeq
).toMap, additionalPlugins = Seq("plugin.InsertTestDataPlugin"))

Then I use running(fakeApp) within each test.

The plugin.InsertTestDataPlugin was another attempt, but it didn't work without defining the plugin in conf/play.plugins -- and that is not wanted, as I only want this code in the test scope.

Should any of these work? Have anyone succeeded with similar options?

Upvotes: 4

Views: 2720

Answers (2)

Arve
Arve

Reputation: 8128

I chose to solve this in another way:

I made a fixture like this:

def runWithTestDatabase[T](block: => T) {
  val fakeApp = FakeApplication(additionalConfiguration = inMemoryDatabase())

  running(fakeApp) {
    ProjectRepositoryFake.insertTestDataIfEmpty()
    block
  }
}

And then, instead of running(FakeApplication()){ /* ... */}, I do this:

class StuffTest extends FunSpec with ShouldMatchers with CommonFixtures {
  describe("Stuff") {
    it("should be found in the database") {
      runWithTestDatabase {       // <--- *The interesting part of this example*
        findStuff("bar").size must be(1);
      }
    }
  }
}

Upvotes: 1

Pere Villega
Pere Villega

Reputation: 16439

Global.onStart should be executed ONCE (and only once) when the application is launched, whatever mode (dev, prod, test) it is in. Try to follow the wiki on how to use Global.

In that method then you can check the DB status and populate. For example in Test if you use an in-memory db it should be empty so do something akin to:

if(User.findAll.isEmpty) {  //code taken from Play 2.0 samples

      Seq(
        User("[email protected]", "Guillaume Bort", "secret"),
        User("[email protected]", "Maxime Dantec", "secret"),
        User("[email protected]", "Sadek Drobi", "secret"),
        User("[email protected]", "Erwan Loisant", "secret")
      ).foreach(User.create)   

  }

Upvotes: 1

Related Questions