session_regenerate_id() - headers already sent in unit testing Yii controller
Asked Answered
S

2

6

I'm trying to unit-test my controller (Yii framework).

/** 
   * @dataProvider provider
   */
  public function testActionEdit_view_login($controller){
    $user = new CWebUser;
    $user->id = 978;
    $identity = new UserIdentity('[email protected]', '123456');
    $user->login($identity);
    $controller->actionEdit();

    $output = ob_get_contents();
    assertContains('Add/Change Profile Picture:', $output);
    assertContains('bio', $output);
    assertContains('specialties', $output);
    assertContains('change login', $output);
    assertContains('New Password', $output);
  }

When I do

$user->login($identity);

in order to login, I get the following error:

session_regenerate_id(): Cannot regenerate session id - headers already sent

I've already tried buffering the output by putting this at the beginning of the class:

public static function setUpBeforeClass(){
  ob_start();
}

I also put ob_clean() in setUp() and ob_end_clean() in tearDownAfterClass().

Still I get the message that headers have already been sent. There are no spaces or newlines in the file, when I comment out the specific test method, it works perfectly. The login() seems to cause the problem.

Anyone got ideas how to prevent this / maybe unit-test the controller differently?

Thanks, MrB

Starwort answered 20/7, 2011 at 1:29 Comment(0)
S
2

Got it. I had included some Yii files before the ob_start(), which seem to have printed the headers. Now I buffer that, too.

Starwort answered 20/7, 2011 at 16:39 Comment(1)
How did you find those? I'm stuck with the same problem, but I can't see anywhere that I've included files.Alleviation
H
4

Before your call to $user->login, add the following code:

$mockSession = $this->getMock('CHttpSession', array('regenerateID'));
Yii::app()->setComponent('session', $mockSession);

This overwrites the regenerateID method with a method that does nothing.

Adding ob_start() to the bootstrap also works, but there is no output from PHPUnit until everything has completed.

With this method, you can still see the progress as it is happening.

I upgraded from Yii 1.1.7 to 1.1.10 and the regenerateID method was added in 1.1.8 so I got this error today.

Hofmannsthal answered 18/7, 2012 at 3:29 Comment(0)
S
2

Got it. I had included some Yii files before the ob_start(), which seem to have printed the headers. Now I buffer that, too.

Starwort answered 20/7, 2011 at 16:39 Comment(1)
How did you find those? I'm stuck with the same problem, but I can't see anywhere that I've included files.Alleviation

© 2022 - 2024 — McMap. All rights reserved.