Skip to content

Instantly share code, notes, and snippets.

@vitorf7 vitorf7/Test.php
Last active Aug 29, 2015

Embed
What would you like to do?
Laravel 5 Testing with Authentication using L5 Helper Methods
<?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' => 'mctest@example.com', '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' => 'mctest@example.com', '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);
}
@vitorf7

This comment has been minimized.

Copy link
Owner Author

commented Mar 5, 2015

I seem to be having a bit of a problem at the moment getting the tests to pass because it seems the

$this->flushSession();

in the tearDown() method is causing this error:

TasksTest::testItCreatesNewTaskGivenValidParameters
ReflectionException: Class session does not exist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.