在功能测试Laravel应用程序时跳过授权

Is there a built-in way to skip authorization completely while testing the controllers?

Sample controller:

public function changePassword(Request $request, LdapInterface $ldap)
{
    $this->authorize('change-password');

    $this->validate($request, [
        'pass' => 'min:8|confirmed|weakpass|required', 
    ]);

    $success = $ldap->updatePassword($request->get('pass'));

    $message = $success ?
        'Your e-mail password has been successfully changed' :
        'An error occured while trying to change your alumni e-mail password.';

    return response()->json(['message' => $message]);
}

I want to skip change-password rule, which is defined inside the AuthServiceProvider like:

public function boot(GateContract $gate)
{
    $gate->define('change-password', function ($user) {
        // Some complex logic here
    });
}

I don't want to add smt. like if (env('APP_ENV') == 'testing') return; inside the code.

I'm not aware of one, but you could move that check to a dedicated middleware and use the withoutMiddleware trait to disable it in tests.

Or you could mock the application's gate instance using Mockery. Mockery is well documented so I'd suggest reading the docs for more details, but setting it up would look something like this:

$mock = Mockery::mock('Illuminate\Contracts\Auth\Access\Gate');
$mock->shouldReceive('authorize')->with('change-password')->once()->andReturn(true);
$this->app->instance('Illuminate\Contracts\Auth\Access\Gate', $mock);

This sets up a mock of the gate contract, sets up what it expects to receive and how it should respond, and then injects it into the application.

From laravel documentation :

When testing your application, you may find it convenient to disable middleware for some of your tests. This will allow you to test your routes and controller in isolation from any middleware concerns. Laravel includes a simple WithoutMiddleware trait that you can use to automatically disable all middleware for the test class:

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use WithoutMiddleware;

    //
}

Or you can use withoutMiddleware() method in you test method like this :

public function testBasicExample()
{
    $this->withoutMiddleware();

    $this->visit('/')
         ->see('Laravel 5');
}

Ps : since Laravel 5.1

Actually there is a built-in way. You can add a "before" callback to be called before actual authorization check and bypass the check simply by returning true:

    \Gate::before(function () {
        return true;
    });

You should add this snippet to either the setUp() method of your test or every test method that you want to bybass the authorization.

It is much simpler. Just take it out of the authorization required section in your routes file. In this example I needed the AssignmentsController to work without Authentication, so I just moved it from the jwt.auth group up:

Route::post('v1/auth/login', 'Api\AuthController@authenticate');
Route::post('v1/auth/sendpassword', 'Api\AuthController@sendPassword');
Route::get('v1/assignments', 'Api\AssignmentsController@getAll');

Route::group(['middleware' => 'jwt.auth'], function() {
  Route::post('v1/auth/logout', 'Api\AuthController@logout');
  Route::post('v1/shipments', 'Api\ShipmentController@getShipments');
  Route::post('v1/assignments/{id}/transfer', 'Api\AssignmentsController@saveAssignment');
  Route::get('v1/shipments/assignments/{assignmentId}', 'Api\AssignmentsController@getDetail');
  Route::post('v1/shipments/assignments/{id}/upload', 'Api\AssignmentsController@uploadFile');
});