alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (FlashCookieSpec.scala)

This example Play Framework source code file (FlashCookieSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

action, api, fakeapplication, flashcookiespec, get, lib, library, ok, option, play, play framework, playspecification, redirect, response, test, withserver, ws

The FlashCookieSpec.scala Play Framework example source code

package play.it.http

import play.api.test._
import play.api.test.Helpers._
import play.api.mvc.{Flash, Action}
import play.api.mvc.Results._
import play.api.libs.ws.{Cookie, Response, WS}
import play.api.Logger

object FlashCookieSpec extends PlaySpecification {

  sequential

  val appWithRedirect = FakeApplication(withRoutes = {
    case ("GET", "/flash") =>
      Action {
        Redirect("/landing").flashing(
          "success" -> "found"
        )
      }
    case ("GET", "/landing") =>
      Action {
        Ok("ok")
      }
  })

  def readFlashCookie(response: Response): Option[Cookie] =
    response.cookies.find(_.name.exists(_ == Flash.COOKIE_NAME))

  "the flash cookie" should {
    "can be set for one request" in new WithServer(app = appWithRedirect, port = 3333) {
      val response = await(WS.url("http://localhost:3333/flash").withFollowRedirects(false).get())
      response.status must equalTo(SEE_OTHER)
      val flashCookie = readFlashCookie(response)
      flashCookie must beSome.like {
        case cookie =>
          cookie.expires must beNone
          cookie.maxAge must beNone
      }
    }

    "be removed after a redirect" in new WithServer(app = appWithRedirect, port = 3333) {
      val response = await(WS.url("http://localhost:3333/flash").get())
      response.status must equalTo(OK)
      val flashCookie = readFlashCookie(response)
      flashCookie must beSome.like {
        case cookie =>
          cookie.expires must beSome.like {
            case expires => expires must be lessThan System.currentTimeMillis()
          }
          cookie.maxAge must beNone
      }
    }
  }


}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework FlashCookieSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.