6

I'm trying to build some tests around a method that reads some data from the session.

I tried extending FakeRequest and overriding the session value, but I get an error on compilation saying that session has to be a val when overriden, which won't work.

How can I modify a FakeRequest() to add values to the session?

Pere Villega
  • 16,429
  • 5
  • 63
  • 100
  • Did you indeed solve this by using the pull request from the accepted answer? Or did you find a way to achieve this without using a modified version of Play? – Arjan Mar 26 '12 at 16:29
  • @arjan hi, no, i didn´t pull it, but I see that´s the solution. Expecting it to be integrated soon – Pere Villega Mar 27 '12 at 09:44

2 Answers2

4

There is a pull request about this functionality

See https://github.com/playframework/Play20/pull/103

Julien Lafont
  • 7,869
  • 2
  • 32
  • 52
4

I used some examples from the pull request to build this in without using an updated version of play:

Create cookie:

val sessionCookie = Session.encodeAsCookie(Session(Map("key" -> "value")))

Create and execute fakeRequest:

val Some(result) = routeAndCall(FakeRequest(GET,"/").withHeaders(play.api.http.HeaderNames.COOKIE -> Cookies.encode(Seq(sessionCookie))))

Then to get stuff out I created the following:

Given the existing style of test methods:

status(result) must equalTo(OK)

I made:

def sessionCookie(result: Result): Option[Cookie] = cookies(result).get("PLAY_SESSION")
def session(result: Result): Session = Session.decodeFromCookie(sessionCookie(result))

Which you call:

  session(result).get("key") must be("value")

Have to say this is not tested in anger. But see if it helps.

minglis
  • 41
  • 2