Assert if return value is redirect or view
Let's say I have this controller for authentication:
class AuthController extends BaseController
{
public function __construct(User $user)
{
$this->user = $user;
}
public function getLogin()
{
if (Auth::check()) {
Session::flash('alert-type', 'error');
Session::flash('alert-message', 'You are already logged in');
return Redirect::to('home');
}
return View::make('auth/login');
}
}
And I have this unit test:
public function testGetLoginWithoutLogin()
{
Auth::shouldReceive('check')->once()->andReturn(false);
View::shouldReceive('make')->once();
$userMock = Mockery::mock('Eloquent', 'User');
$authController = new AuthController($userMock);
$authController->getLogin();
}
How can I make sure the view is returned? And in another unit test with a valid login, how would I test it, does the redirect return?
+3
source to share
2 answers
You can check the return type getLogin()
.
To redirect
$returnValue = $authController->getLogin();
$this->assertInstanceOf('\Illuminate\Http\RedirectResponse', $returnValue);
For presentation
$returnValue = $authController->getLogin();
$this->assertInstanceOf('\Illuminate\View\View', $returnValue);
0
source to share
Use with()
to check that your view is getting the correct template:
View::shouldReceive('make')->once()->with('auth/login');
... and then, to test for redirects, there are some useful assertions that are built into Laravel , so:
// once you make your simulated request
$this->call('GET', 'URL-that-should-redirect');
// (or simulate a get to the action on your Controller.. )
$this->action('GET', 'Controller@action');
//you can check that a redirect simply happens:
$this->assertResponseStatus(302); // would also work with any HTTP status
// ...or even check that you get redirected to
// a particular URL ...
$this->assertRedirectedTo('foo');
// ... route ...
$this->assertRedirectedToRoute('route.name');
// ...or controller action
$this->assertRedirectedToAction('Controller@method');
0
source to share