Downloads
Stars
Version
Testing contains traits with helpers for testing models and controllers in Laravel. It helps you assert the validity of your models (assuming the use of watson/validating) as well as the relationships of your models. It also allows you to test the responses of your controllers.
Simply run the following Composer command in your application.
composer require watson/testing
The ~1.0
stream is for Laravel 4, and the ~2.0
stream is for Laravel 5.
To use the test helpers in your tests, simply bring the trait in to your test file.
class UsersControllerTest extends TestCase {
use Watson\Testing\ControllerHelpers;
}
class UserTest extends TestCase {
use Watson\Testing\ModelHelpers;
}
If you'd prefer to use the test helpers globally, just use this trait in your TestCase.php
.
class TestCase extends Illuminate\Foundation\Testing\TestCase {
use Watson\Testing\TestingTrait;
}
// Controller
return View::make('users.index');
// Test
$this->assertViewIs('users.index');
Ensure that the view used in the response is the one you expected.
If you're using watson/validating on your models it is really easy to test your validations. We will use the following User
model for these examples.
$user = new User;
$user->email = '[email protected]';
$this->assertValid($user);
$user->email = 'foo';
$this->assertInvalid($user);
If you want to easily check if a model is valid or invalid with or without a certain attribute, there a number of helpers for quickly asserting that this is the case.
$this->assertValidWith($user, 'email', '[email protected]');
$this->assertValidWithout($user, 'last_name')
$this->assertInvalidWith($user, 'email', 'foo');
$this->assertInvalidWithout($user, 'email');
If you'd prefer an easier (and more readable) way of asserting the validations on your model you might like to try specific model validations. They work with watson/validating or any other validation trait that complies with Watson\Validating\ValidatingInterface
(that is, has a getDefaultRules
method).
// Assert that the email attribute is required.
$this->assertValidatesWith($user, 'email', 'required');
$this->assertValidatesRequired($user, 'email');
Here is the list of included Laravel default validation assertions:
You can assert the different relationships exist on your model.
Ensure that a post belongs to a user.
$this->assertBelongsTo($post, 'user');
Ensure that a tag belongs to many posts.
$this->assertBelongsToMany($tag, 'posts');
Ensure that a user has one profile.
$this->assertHasOne($user, 'profile');
Ensure that a user has many posts.
$this->assertHasMany($user, 'posts');
This package builds upon the work of the now unmaintained way/laravel-test-helpers and includes code from the unmerged pull requests of SammyK, effi, mrevd and sorora.
I decided to continue the development of these helpers because I prefer testing with the tool that ships with the framework, and I really like PHPUnit.