lundi 18 novembre 2019

Testing method store data in to tables in Laravel

I've a method for create a new user, that create a new row in other table domains. I only think that I can do the test, if when I return the api response, I return the user and domain data, which I don't think is the best way

USerController

public function store(Request $request)
{
    if (!Auth::user()->is_super_admin) {
        return  $this->sendError(
            'The user does not have permissions for the request',
            [],
            Response::HTTP_FORBIDDEN
        );
    }


    $rules = Validator::make($request->all(), [
        'name' => 'required|max:255',
        'email' => 'required|unique:users,email',
        'password' => 'required',
        'c_password' => 'required|same:password',
        'domain' => 'required|unique:domains,domain'
    ]);

    if ($rules->fails()) {
        return $this->sendError('Validation Error.', $rules->errors(), Response::HTTP_BAD_REQUEST);
    }

    DB::beginTransaction();

    try {
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);

        $user = User::create($input);

        $success['token'] = $user->createToken('Albarid')->accessToken;
        $success['name'] = $user->name;

        $domain = new Domain;
        $domain->domain = $input['domain'];
        $domain->user_id = $user->id;
        $domain->save();
    } catch (\Exception $e) {
        DB::rollBack();
        return $this->sendError(
            'Problem when saving on database',
            [$e->getMessage()],
            Response::HTTP_BAD_GATEWAY
        );
    }

    DB::commit();

    return $this->sendResponse($success, 'User register successfully');
}

Test

function super_admin_add_user()
{
    Passport::actingAs(factory(User::class)->create(['is_super_admin' => true]));

    $name = 'John Doe';
    $domain = 'johndoe.com';

    $params = [
        'name'       => $name,
        'email'      => 'john@doe.com',
        'password'   => '123456',
        'c_password' => '123456',
        'domain'     => $domain,
    ];

    $response = $this->json('POST', '/api/v1/users', $params);

    $response
        ->assertStatus(200)
        ->assertJsonPath('data.name', $name);

    // Check if create domain
    $new_domain = Domain::find($domain);


    //$second = $this->assertEquals($domain, $new_domain->domain))

}

Aucun commentaire:

Enregistrer un commentaire