Question

I'm trying to get familiar with PHPUnit testing within Kohana. At the moment, I seem to be having problems with Request::current()->redirect calls in my code.

For example, I am trying to test the login functionality. Once our user is successfully logged in, we redirect it to its home page using the above Request redirect line. The problem is that when that line is there, the test seems to stop there and never return the results.

Here is how my tests is written at the moment:

class SampleTest extends Kohana_UnitTest_TestCase
{
protected $session;

public function setUp() {
    parent::setUp();
    $this->session = Session::instance();
}

public function testLogin()
{   
    $request = new Request('/login');
    $request->method(HTTP_Request::POST)
        ->post(array('username' => 'username', 'password' => 'password'));
    $request->execute();

    $this->assertEquals($this->session->get('username'), 'password');
 }
}

If I comment out the following line in my login controller, everything works great:

Request::current()->redirect(); //redirect to home

What am I doing wrong?

Was it helpful?

Solution

The order of operations for a standard request (check your index.php) is:

  1. execute
  2. send_headers
  3. body

You hijacked the request in the middle of your execute and redirected the process. Your test simply follows that code since it is all part of that execute.

Instead, defer your redirect by adding it to the Request headers which get executed in send_headers and you won't hit that code in your unittest. Replace your Request::current()->redirect() line with the proper way to redirect users:

$this->response->headers("Location", URL::site(NULL, TRUE));

OTHER TIPS

I think the best way to test redirects in Kohana is to extend the Request class with a Unittest_Request.

Add a redirect method to the Unittest_Request class which uses the Location header.

Add some helper methods to your tests for creating get and post requests using Unittest requests.

Write assert methods like assertRedirectedTo, assertResponse.... and so on.

I know this is a lot, but it would really help you in a longer term.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top