How to follow redirects inside test cases?

1.6k views Asked by At

Based on: Testing a page that is loaded after a redirect

Play!2.0 Framework (Scala) does have API which we can use to make redirects. However is there any way in Play Framework ( Scala ) that the test case automatically follows redirect responses. I would not want to repeat the redirect logic every time.

How to follow redirects inside test cases for Play Framework ( Scala ) ?

1

There are 1 answers

2
Michael Zajac On

Edit: To make it completely clear. There isn't a built-in way to do this, and for a good reason. Unit tests are supposed to be simple and isolated. A single unit test is meant to test a single piece of functionality.

Example: You make a GET request to a page that needs authentication, but you provide no credentials, so the server responds with SEE OTHER and a flash message attached. You then make sure it responded to that request appropriately. Test over. The controller function that responds with SEE OTHER should have no knowledge of the other, other than maybe it'll do something with that flash data.

Example 2: You make a GET request to a login page with flash data attached. The server responds with OK and an HTML view displaying the flash message within it. You make sure it does so.

If you really want to tie these two together, then perhaps tests using WithBrowser would suit you more.


If you're testing redirect information, it's better to isolate it from whatever controller function/view the redirect is pointing to. There are test helpers you can use to achieve this.

Let's say you want to test

Redirect("/login").flashing("message" -> "You are not logged in.")

In your test you could use these helpers:

import play.api.test._

val request = FakeRequest(GET, "/secretpage")
val Some(result) = route(request)
status(result) must equalTo(SEE_OTHER)
redirectLocation(result) must beSome("/login")
flash(result).get("message") must beSome("You are not logged in.")

Note that this is for Play 2.1.x and above. If you're using 2.0.x, you should change route to routeAndCall.