Last active
August 29, 2015 14:16
-
-
Save vitorf7/e87af0c4afc065f1de83 to your computer and use it in GitHub Desktop.
Laravel 5 Testing with Authentication using L5 Helper Methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// === Inside my ApiTester.php Class. Could be inside the same test class but I use this for methods to test my API === // | |
/** | |
* Set Up Method for Tests | |
*/ | |
public function setUp() | |
{ | |
parent::setUp(); | |
Artisan::call('migrate'); | |
$this->session(array()); | |
$this->testSession = Session::all(); | |
} | |
/** | |
* Tear Down Method for Tests | |
*/ | |
public function tearDown() | |
{ | |
parent::tearDown(); | |
} | |
/** | |
* Method to stub a new Task | |
* Uses faker library to create mock content | |
* | |
* @param array $fields | |
* | |
* @return array | |
*/ | |
public function getStub($fields = array()) | |
{ | |
return array_merge(array( | |
'user_id' => 1, | |
'title' => (string) $this->faker->sentence(3), | |
'description' => (string) $this->faker->realText(100), | |
'completed' => $this->faker->boolean() | |
), $fields); | |
} | |
/** | |
* Method to create new User and then Authenticate the User | |
* http://laravel.com/docs/5.0/testing#helper-methods | |
*/ | |
public function getAuthenticatedUser() | |
{ | |
$user = new User(['name' => 'McTest', 'email' => '[email protected]', 'password' => Hash::make('password')]); | |
$this->be($user); | |
} | |
/** | |
* Method to create new User and then Authenticate the User | |
* http://laravel.com/docs/5.0/testing#helper-methods | |
*/ | |
public function getAuthenticatedUser() | |
{ | |
$user = new User(['name' => 'McTest', 'email' => '[email protected]', 'password' => Hash::make('password')]); | |
$this->be($user); | |
} | |
/** | |
* Method to return the _token for the Session to use during tests that need to | |
* pass through the CSRF middleware | |
* | |
* @return array | |
*/ | |
public function getSessionCsrftoken() | |
{ | |
return array( '_token' => $this->testSession['_token']); | |
} | |
// === In the test file itself. === // | |
/** | |
* Test a new task is successfully created | |
*/ | |
public function testItCreatesNewTaskGivenValidParameters() | |
{ | |
$this->getAuthenticatedUser(); | |
$this->getJson('api/v1/tasks', 'POST', array_merge($this->getStub(), $this->getSessionCsrftoken())); | |
$this->assertResponseStatus(201); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I seem to be having a bit of a problem at the moment getting the tests to pass because it seems the
in the tearDown() method is causing this error: