有没有办法在运行 PHP laravel 测试套件时防止重定向?

问题描述 投票:0回答:1

我正在尝试将 Pest 和单元测试添加到 Nova Admin/Laravel 应用程序。

我想测试一个页面是否存在,但我不想处理用户是否通过管理员身份验证来查看该页面。我正在尝试测试页面是否存在,无论用户是否登录、是否具有特定角色、是否具有特定权限等。

每次运行依赖于路由的测试时,页面都会重定向到登录页面。如何禁用重定向并绕过所有角色/权限/身份验证相关设置来简单测试页面内容?


class ExampleTest extends TestCase
{

    public function test_it_should_have_a_login_page()
    {
        $response = $this->get('/login');
        $response->assertStatus(200);  //<-- this passes
    }

    
    public function test_it_should_have_a_routing_resources_page()
    {

        $response = $this
                ->withoutMiddleware(\App\Http\Middleware\Authenticate::class)
                ->withoutMiddleware(\App\Http\Middleware\RedirectIfAuthenticated::class)
                ->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class)
                ->get('/resources/routing');
        $response->assertStatus(200);  //<-- this fails with status of 302: the page has redirected to /login
    }
}


另一次不成功的尝试:

 public function test_it_should_have_a_routing_resources_page()
    {
        $user = User::factory()->create();
        $role = NovaRole::create(['name' => 'admin', 'updated_at' => now(), 'created_at' => now(), 'slug' => 'admin']);
        $user->assignRole($role->name);
        $permissions = config('nova-permissions.permissions');
        foreach ($permissions as $permission) {
            $user->hasPermissionTo($permission);
        }

        $response = $this
                ->actingAs($user)
                ->withoutMiddleware(\App\Http\Middleware\Authenticate::class)
                ->withoutMiddleware(\App\Http\Middleware\RedirectIfAuthenticated::class)
                ->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class)
                ->get('/resources/routing');
        $response->assertStatus(200); //<-- now this fails and returns 403, forbidden
    }
php laravel laravel-nova php-pest
1个回答
0
投票

啊哈!!我试图绕过错误的中间件。真正帮助解决这个问题的是进入

nova.php
并注释掉
'api_middleware'
中的每个条目,直到我找到阻止测试调用的中间件。

工作代码如下:


public function test_it_should_have_a_routing_resources_page()
    {
        $user = User::factory()->create();
        $permissions = config('nova-permissions.permissions');
        foreach ($permissions as $permission) {
            $user->hasPermissionTo($permission);
        }

        $response = $this
                ->actingAs($user)
                ->withoutMiddleware(Laravel\Nova\Http\Middleware\Authenticate::class) //<-- this was the issue
                ->get('/resources/routing');
        $response->assertStatus(200);
    }
© www.soinside.com 2019 - 2024. All rights reserved.