score:11

Accepted answer

Update : Like haui said in his comment :

Seems like they added something similar in play version 2.6. There you can use import play.api.test.CSRFTokenHelper._ FakeRequest().withCSRFToken (Scala) and CSRFTokenHelper.addCSRFToken(requestBuilder) (Java) as explained in the Migration guide

For people who are still in 2.5.6, my answer still apply :

So, after looking in Play-scala classes for a certain time, I finally found a way to adapt this answer : https://stackoverflow.com/a/19849420/4496364 to Play 2.5.6

I even made a trait, so if someone need it one day, here it is :

import play.api.Application
import play.api.test.FakeRequest
import play.filters.csrf.CSRF.Token
import play.filters.csrf.{CSRFConfigProvider, CSRFFilter}

import scala.language.postfixOps

trait CSRFTest {
  def addToken[T](fakeRequest: FakeRequest[T])(implicit app: Application) = {
    val csrfConfig     = app.injector.instanceOf[CSRFConfigProvider].get
    val csrfFilter     = app.injector.instanceOf[CSRFFilter]
    val token          = csrfFilter.tokenProvider.generateToken

    fakeRequest.copyFakeRequest(tags = fakeRequest.tags ++ Map(
      Token.NameRequestTag  -> csrfConfig.tokenName,
      Token.RequestTag      -> token
    )).withHeaders((csrfConfig.headerName, token))
  }
}

To use it, simply extend your test class with it, like this :

class LoginSpec extends PlaySpec with OneAppPerSuite /* or whatever OneApp */ with CSRFTest

then, instead of calling

val fakeRequest = FakeRequest(/* params */)

simply call

val fakeRequest = addToken(FakeRequest(/* params */))

I tried to make it look like the addToken{} in the Controller :)


Related Query

More Query from same tag