Lee Pownall

Testing Laravel Rule Objects

Outdated!

Warning! This post is old and may contain out of date advice.

Laravel gives you the ability to create custom validation rules using rule objects, these allow you to create any validation rules you want, but how do you test them?

You could create a Feature test that visits a route, enters wrong data, presses submit and then asserts an error message is shown, but that is long-winded.

Instead, we can create a Unit test that just tests the rule in isolation. In this example we will be testing the example rule given in the documentation.

Start by creating your test class:

1<?php
2 
3namespace Tests\Unit\Rules;
4 
5class UppercaseRuleTest extends \Tests\TestCase
6{
7 /** @test **/
8 public function uppercase_string_passes()
9 {
10 //
11 }
12}

Inside your first test create a new instance of the Uppercase rule:

1<?php
2 
3$rule = new Uppercase();

Then simply assert against the passes() method, giving it an example attribute and value. The attribute you give it doesn't matter, it can be anything:

1<?php
2 
3$this->assertTrue($rule->passes('name', 'JEFF'));

Putting it all together you get:

1<?php
2 
3/** @test **/
4public function uppercase_string_passes()
5{
6 $rule = new Uppercase();
7 
8 $this->assertTrue(
9 $rule->passes('name', 'JEFF'),
10 'String given must be `uppercase`.'
11 );
12}

Hopefully this example shows how easy it is to test Rule Objects. Below is an example of some other test cases you could write:

1<?php
2 
3/** @test **/
4public function lowercase_string_does_not_pass()
5{
6 $rule = new Uppercase();
7 
8 $this->assertFalse(
9 $rule->passes('name', 'jeff'),
10 'String given must be `uppercase`.'
11 );
12}
13 
14/** @test **/
15public function uppercase_and_lowercase_string_does_not_pass()
16{
17 $rule = new Uppercase();
18 
19 $this->assertFalse(
20 $rule->passes('name', 'JeFf'),
21 'String given must be `uppercase`.'
22 );
23}