Deon
Deon

Reputation: 193

Laravel Test Custom Blade If

I'm trying to unit test custom blade if in laravel.

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\Compilers\BladeCompiler;

class BladeIfAdminStatementTest extends TestCase
{
    public function testIfAdminStatementAreCompiled()
    {
        $compiler = new BladeCompiler(\Mockery::mock(Filesystem::class), __DIR__);

        $string = '@admin test @endadmin';
        $expected = '<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>';

        $this->assertEquals($expected, $compiler->compileString($string));
    }
}

In AppServiceProvider.php

<?php


...

public function boot()
{
    \Blade::if('admin', function () {
        return auth()->check() && auth()->user()->isAdmin();
    });
}

When I run phpunit I'm getting:

Failed asserting that two strings are equal.
Expected :'<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>'
Actual   :'@admin  test @endadmin'

When I try and change the $string from @admin test @endadmin to @if(true) test @endif and running phpunit:

Failed asserting that two strings are equal.
Expected :'<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>'
Actual   :'<?php if(true): ?> test <?php endif; ?>'

Notice that it fails but still, The @if statement is compiled correctly while my custom @admin statement isn't.

Upvotes: 1

Views: 648

Answers (2)

Didwiz
Didwiz

Reputation: 182

Just access the compileString method like this:

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\Blade;


class BladeIfAdminStatementTest extends TestCase
{
    public function testIfAdminStatementAreCompiled()
    {

        $bladeSnippet = '@admin test @endadmin';
        $expectedCode = '<?php if(auth->check() && auth()->user()->isAdmin()): ?> test <?php endif; ?>';

        $this->assertEquals($expectedCode, Blade::compileString($bladeSnippet));
    }
}

Upvotes: 1

Marabesi
Marabesi

Reputation: 94

the compileString will compile the string and return for you the result of the code.

Each blade statement is going to be avaluated and then returned.

have you tried to assert the result instead of the php code?

Upvotes: 0

Related Questions