测试重定向后加载的页面

Ren*_*Ren 3 scala playframework specs2

我有一个测试用例,应该验证在POST调用后,用户被重定向到正确的页面.

"Redirect Page" in {
  running(FakeApplication()) {
    val Some(result) = route(FakeRequest(POST, "/product/add/something")
      .withFormUrlEncodedBody(
       "Id" -> "666",
      )
      .withSession("email" -> "User")
    )
    status(result) must equalTo(SEE_OTHER)
    // contentAsString(result) at this point is just blank
Run Code Online (Sandbox Code Playgroud)

这将验证是否提供了重定向URL.然后,我如何让单元测试转到重定向的URL,以便我可以验证其内容?

ash*_*ley 7

您可以测试重定向到的URL:

    redirectLocation(result) must beSome.which(_ == "/product/666")
Run Code Online (Sandbox Code Playgroud)

如果要检查内容,请按照重定向:

    val nextUrl = redirectLocation(result) match {
      case Some(s: String) => s
      case _ => ""
    }
    nextUrl must contain("/product/666")

    val newResult = route(FakeRequest(GET, nextUrl)).get

    status(newResult) must equalTo(OK)
    contentType(newResult) must beSome.which(_ == "text/html")
    contentAsString(newResult) must contain("something")
Run Code Online (Sandbox Code Playgroud)