简体   繁体   中英

Laravel Testing auth middleware

When feature testing my app, I find myself writing pretty much the same tests to verify that my controllers require authentication. It usually looks something like this:

public function a_guest_cannot_view_any_of_the_pages()
{
    $this->withExceptionHandling();

    $model = factory(Model::class)->create();

    $response = $this->get(route('models.show', [ 'id' => $model->id ]));
    $response->assertRedirect(route('login'));

    $response = $this->get(route('models.edit', [ 'id' => $model->id ]));
    $response->assertRedirect(route('login'));

   ...etc 
}

However, I find it unnecessarily cumbersome to test it like this for every controller that requires authentication.

Is there any tactics for testin CRUD with auth middleware? How do I improve this?

you can use a data provider:

in tests/TestCase.php:

/**
* @dataProvide dataProvider
*/
public function testRedirectToAuth($routeName)
    {
    $this->withExceptionHandling();

    $model = factory(Model::class)->create();

    $response = $this->get(route($routeName, [ 'id' => $model->id ]));
    $response->assertRedirect(route('login'));
}

and then you can call it in all the test cases:

public function dataProvider()
{
  return [
    'model.show',
    'model.edit',
    ...
  ];
}

Solution 1 Define the middleware in the controller constructor that will act on all functions

public function __construct()
{
    $this->middleware('auth');
}

ou Solution 2 Define the middleware directly on the route

Route::get('admin/profile', function () {
    //
})->middleware('auth');

https://laravel.com/docs/5.7/middleware

You could use a ShowTrait , when using this trait you have to specify your route and model name.

<?php

class ModelTest extends Test
{
    use ShowTrait;

    protected $routebase = 'api.v1.models.';
    protected $model = Model::class;
}

abstract class Test extends TestCase
{
    use RefreshDatabase, InteractsWithDatabase, UseAuthentication;

    protected $routebase = 'api.v1.';
    protected $model;

    /**
     * @test
     */
    public function is_valid_model()
    {
        $this->assertTrue(class_exists($this->model));
    }
}

trait ShowTrait {

    public function test_show_as_authenticated_user()
    {
        $record = factory($this->model);

        $this->assertShow($record)
    }


    protected function assertShow($record)
    {
        $route = route($this->routebase . "show", ['id' => $record->id]);

        // Get response
        $response = $this->get($route);
        $response->assertRedirect(route('login'));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM