Las pruebas de Laravel fallaron afirmar que dos cadenas son iguales -- laravel campo con testing campo con phpunit camp Relacionados El problema

Laravel testing Failed asserting that two strings are equal


0
vote

problema

Español

Soy muy nuevo en la prueba, pero ahora lo he encontrado esencial para automatizar mis pruebas.

Tengo una prueba que está funcionando bien hasta que llegue al enlace '/ carro', llega al enlace '/ carro' sin problema, pero cualquier otro enlace que intento hacer clic siempre siempre termina en el carrito .

Aquí está mi error después de intentar navegar desde el carrito.

  Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'http://ngwenya-mtb.dev/events' +'http://ngwenya-mtb.dev/cart'   

y aquí está mi script de prueba

  use IlluminateFoundationTestingWithoutMiddleware; use IlluminateFoundationTestingDatabaseMigrations; use IlluminateFoundationTestingDatabaseTransactions;  class ExampleTest extends TestCase {     //use IlluminateFoundationTestingWithoutMiddleware; //use DatabaseTransactions;  //use withoutMiddleware; //use DatabaseMigrations; /**  *   * A basic functional test example.  * Please choose a unique email address for your new participant  * @return void  */ public function testNewUserRegistration() {      $this->visit('http://ngwenya-mtb.dev/')         // View Event         ->click('View event details')         ->seePageIs('/event?id=30')          ->click('#enter-race47')         ->press('Enter yourself to this race')          ->seePageIs('/events/courses/register/addtocart')         //->withSession(['This email is already registered' => 'alert-danger'])          /////////////////////////////////////////////         //  Fill the register for for new user         /////////////////////////////////////////////         ->type('Bingo', 'first_name')         ->type('11111111', 'password')         ->type('11111111', 'password_confirmation')         ->type(''.substr(md5(time()), 0, 12).'@tesing.com', 'email')         //->check('terms')         ->select('Male', 'gender')         ->select('1985', 'year')         ->select('07', 'month')         ->select('21', 'day')         ->select('Small', 'shirt_size')         ->select('Swaziland ID', 'id_type')         ->type('badassnumber', 'id_number')         ->select('Swazi', 'nationality')         //Contact details Physical         ->type('Dawlish', 'town_physical')         ->select('Swaziland', 'country_physical')         ->type('864741', 'phone_cell')         //Emergency contact details 1         ->type('Simon', 'emergency_contact_1')         ->type('Brother', 'emergency_relationship_1')         ->type('864741', 'emergency_phone_1');           $this->press('Register');         $this->seePageIs('/cart');           /////////////////////////////////////////////         //  Add a new user         /////////////////////////////////////////////          $this->visit('http://ngwenya-mtb.dev/');         $this->click('#events-link')          ->seePageIs('/events');         dd($this->response->getContent());exit;         $this->click('#event-30');         $this->seePageIs('/event?id=30');          $this->click('#enter-race48');         $this->press('Enter someone else to this race');         $this->seePageIs('/events/courses/register/addtocart');                  }  }   

Todo está funcionando bien hasta este comentario

  ///////////////////////////////////////////// //  Add a new user /////////////////////////////////////////////   

Aquí está mi controlador de registro

  <?php  namespace AppHttpControllers;  use VinklaHashidsHashidsManager; use IlluminateRoutingController as BaseController; use SentinelFormRequestsRegisterRequest; use SentinelFormRequestsEmailRequest; use SentinelFormRequestsResetPasswordRequest; use SentinelRepositoriesGroupSentinelGroupRepositoryInterface; use SentinelRepositoriesUserSentinelUserRepositoryInterface; use SentinelTraitsSentinelRedirectionTrait; use SentinelTraitsSentinelViewfinderTrait; use Sentry; use View; use Request; use Event; use Redirect; use Session; use Config; use AppModelsUsers; use IlluminateSupportFacadesInput; use GloudemansShoppingcartFacadesCart;  class RegistrationController extends BaseController {     /**      * Traits      */     use SentinelRedirectionTrait;     use SentinelViewfinderTrait;      /**      * Constructor      */     public function __construct(         SentinelUserRepositoryInterface $userRepository,         SentinelGroupRepositoryInterface $groupRepository,         HashidsManager $hashids     ) {         $this->userRepository       = $userRepository;         $this->groupRepository      = $groupRepository;         $this->hashids              = $hashids;     }      /**      * Show the registration form, if registration is allowed      *      * @return Response      */     public function registration()     {         // Is this user already signed in? If so redirect to the post login route         if (Sentry::check()) {             return $this->redirectTo('session_store');         }          //If registration is currently disabled, show a message and redirect home.         if (! config('sentinel.registration', false)) {             return $this->redirectTo(['route' => 'home'], ['error' => trans('Sentinel::users.inactive_reg')]);         }          // All clear - show the registration form.         return $this->viewFinder(config('sentinel.view.user_register', 'Sentinel::users.register'));     }      /**      * Process a registration request      *      * @return Response      */     public function register(RegisterRequest $request)     {          // Gather input         $data = $request->all();          // collect cart items         $email = Input::get('email');         $course_id = Input::get('course_id');         $event_name = Input::get('event_name');         $entry_fee = Input::get('entry_fee');          // check user exists         if (Users::where('email', '=', $email)->exists()) {             // user found             $request->session()->flash('alert-danger', 'Warning: This email is already registered.');             Input::flash();             return View::make('sentinel.users.register')                     ->with('course_id',$course_id)                     ->with('event_name',$event_name)                     ->with('entry_fee',$entry_fee);         }          // Add user and course to cart         if ($course_id) {             $firstUserRowId = Cart::add($course_id, $event_name , 1, $entry_fee, [                       'first_name' => Input::get('first_name'),                     'last_name' => Input::get('last_name'),                      'email' => Input::get('email'),                     'no_email' => 0,                     'master_user' => 1,                     'gender' => Input::get('gender'),                     'dob' => Input::get('dob'),                     'shirt_size' => Input::get('shirt_size'),                     'id_type' => Input::get('id_type'),                     'id_number' => Input::get('id_number'),                     'nationality' => Input::get('nationality'),                     'phone_cell' => Input::get('phone_cell'),                     'town_physical' => Input::get('town_physical'),                     'country_physical' => Input::get('country_physical'),                     'emergency_contact_1' => Input::get('emergency_contact_1'),                     'emergency_relationship_1' => Input::get('emergency_relationship_1'),                     'emergency_phone_1' => Input::get('emergency_phone_1'),                 ]);                      }            // get email from request         $email = $request->only('email');         foreach ($email as $userModel) {}          // Edit date of birth from request         $year = Input::get('year');         $month = Input::get('month');         $day = Input::get('day');                $dob = $year.'-'.$month.'-'.$day;         $data['dob'] = $dob;          // Attempt Registration         $result = $this->userRepository->store($data);                                  // Log user in         FunctionsController::loginUser($userModel);          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_complete', $result);     }      /**      * Activate a new user      *      * @param  int    $id      * @param  string $code      *      * @return Response      */     public function activate($hash, $code)     {         // Decode the hashid         $id = $this->hashids->decode($hash)[0];          // Attempt the activation         $result = $this->userRepository->activate($id, $code);          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_activated', $result);     }      /**      * Show the 'Resend Activation' form      *      * @return View      */     public function resendActivationForm()     {         return $this->viewFinder('Sentinel::users.resend');     }      /**      * Process resend activation request      * @return Response      */     public function resendActivation(EmailRequest $request)     {         // Resend the activation email         $result = $this->userRepository->resend(['email' => e($request->get('email'))]);          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_resend', $result);     }      /**      * Display the "Forgot Password" form      *      * @return IlluminateViewView      */     public function forgotPasswordForm()     {         return $this->viewFinder('Sentinel::users.forgot');     }       /**      * Process Forgot Password request      * @return Response      */     public function sendResetPasswordEmail(EmailRequest $request)     {         // Send Password Reset Email         $result = $this->userRepository->triggerPasswordReset(e($request->get('email')));          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_reset_triggered', $result);     }      /**      * A user is attempting to reset their password      *      * @param $id      * @param $code      *      * @return Redirect|View      */     public function passwordResetForm($hash, $code)     {         // Decode the hashid         $id = $this->hashids->decode($hash)[0];          // Validate Reset Code         $result = $this->userRepository->validateResetCode($id, $code);          if (! $result->isSuccessful()) {             return $this->redirectViaResponse('registration_reset_invalid', $result);         }          return $this->viewFinder('Sentinel::users.reset', [             'hash' => $hash,             'code' => $code         ]);     }      /**      * Process a password reset form submission      *      * @param $hash      * @param $code      * @return Response      */     public function resetPassword(ResetPasswordRequest $request, $hash, $code)     {         // Decode the hashid         $id = $this->hashids->decode($hash)[0];          // Gather input data         $data = $request->only('password', 'password_confirmation');          // Change the user's password         $result = $this->userRepository->resetPassword($id, $code, e($data['password']));          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_reset_complete', $result);     } }   
Original en ingles

I am very new to testing, but have now found it essential to automate my testing.

I have a test that is working fine up until it gets to the link '/cart' it gets to the link '/cart' no problem, but any other link I try to click afterwards always ends up back at the cart.

here is my error after trying to navigate away from the cart.

Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'http://ngwenya-mtb.dev/events' +'http://ngwenya-mtb.dev/cart' 

And here is my test script

use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions;  class ExampleTest extends TestCase {     //use Illuminate\Foundation\Testing\WithoutMiddleware; //use DatabaseTransactions;  //use withoutMiddleware; //use DatabaseMigrations; /**  *   * A basic functional test example.  * Please choose a unique email address for your new participant  * @return void  */ public function testNewUserRegistration() {      $this->visit('http://ngwenya-mtb.dev/')         // View Event         ->click('View event details')         ->seePageIs('/event?id=30')          ->click('#enter-race47')         ->press('Enter yourself to this race')          ->seePageIs('/events/courses/register/addtocart')         //->withSession(['This email is already registered' => 'alert-danger'])          /////////////////////////////////////////////         //  Fill the register for for new user         /////////////////////////////////////////////         ->type('Bingo', 'first_name')         ->type('11111111', 'password')         ->type('11111111', 'password_confirmation')         ->type(''.substr(md5(time()), 0, 12).'@tesing.com', 'email')         //->check('terms')         ->select('Male', 'gender')         ->select('1985', 'year')         ->select('07', 'month')         ->select('21', 'day')         ->select('Small', 'shirt_size')         ->select('Swaziland ID', 'id_type')         ->type('badassnumber', 'id_number')         ->select('Swazi', 'nationality')         //Contact details Physical         ->type('Dawlish', 'town_physical')         ->select('Swaziland', 'country_physical')         ->type('864741', 'phone_cell')         //Emergency contact details 1         ->type('Simon', 'emergency_contact_1')         ->type('Brother', 'emergency_relationship_1')         ->type('864741', 'emergency_phone_1');           $this->press('Register');         $this->seePageIs('/cart');           /////////////////////////////////////////////         //  Add a new user         /////////////////////////////////////////////          $this->visit('http://ngwenya-mtb.dev/');         $this->click('#events-link')          ->seePageIs('/events');         dd($this->response->getContent());exit;         $this->click('#event-30');         $this->seePageIs('/event?id=30');          $this->click('#enter-race48');         $this->press('Enter someone else to this race');         $this->seePageIs('/events/courses/register/addtocart');                  }  } 

Everything is working fine up until this comment

///////////////////////////////////////////// //  Add a new user ///////////////////////////////////////////// 

Here is my Registration controller

<?php  namespace App\Http\Controllers;  use Vinkla\Hashids\HashidsManager; use Illuminate\Routing\Controller as BaseController; use Sentinel\FormRequests\RegisterRequest; use Sentinel\FormRequests\EmailRequest; use Sentinel\FormRequests\ResetPasswordRequest; use Sentinel\Repositories\Group\SentinelGroupRepositoryInterface; use Sentinel\Repositories\User\SentinelUserRepositoryInterface; use Sentinel\Traits\SentinelRedirectionTrait; use Sentinel\Traits\SentinelViewfinderTrait; use Sentry; use View; use Request; use Event; use Redirect; use Session; use Config; use App\Models\Users; use Illuminate\Support\Facades\Input; use Gloudemans\Shoppingcart\Facades\Cart;  class RegistrationController extends BaseController {     /**      * Traits      */     use SentinelRedirectionTrait;     use SentinelViewfinderTrait;      /**      * Constructor      */     public function __construct(         SentinelUserRepositoryInterface $userRepository,         SentinelGroupRepositoryInterface $groupRepository,         HashidsManager $hashids     ) {         $this->userRepository       = $userRepository;         $this->groupRepository      = $groupRepository;         $this->hashids              = $hashids;     }      /**      * Show the registration form, if registration is allowed      *      * @return Response      */     public function registration()     {         // Is this user already signed in? If so redirect to the post login route         if (Sentry::check()) {             return $this->redirectTo('session_store');         }          //If registration is currently disabled, show a message and redirect home.         if (! config('sentinel.registration', false)) {             return $this->redirectTo(['route' => 'home'], ['error' => trans('Sentinel::users.inactive_reg')]);         }          // All clear - show the registration form.         return $this->viewFinder(config('sentinel.view.user_register', 'Sentinel::users.register'));     }      /**      * Process a registration request      *      * @return Response      */     public function register(RegisterRequest $request)     {          // Gather input         $data = $request->all();          // collect cart items         $email = Input::get('email');         $course_id = Input::get('course_id');         $event_name = Input::get('event_name');         $entry_fee = Input::get('entry_fee');          // check user exists         if (Users::where('email', '=', $email)->exists()) {             // user found             $request->session()->flash('alert-danger', 'Warning: This email is already registered.');             Input::flash();             return View::make('sentinel.users.register')                     ->with('course_id',$course_id)                     ->with('event_name',$event_name)                     ->with('entry_fee',$entry_fee);         }          // Add user and course to cart         if ($course_id) {             $firstUserRowId = Cart::add($course_id, $event_name , 1, $entry_fee, [                       'first_name' => Input::get('first_name'),                     'last_name' => Input::get('last_name'),                      'email' => Input::get('email'),                     'no_email' => 0,                     'master_user' => 1,                     'gender' => Input::get('gender'),                     'dob' => Input::get('dob'),                     'shirt_size' => Input::get('shirt_size'),                     'id_type' => Input::get('id_type'),                     'id_number' => Input::get('id_number'),                     'nationality' => Input::get('nationality'),                     'phone_cell' => Input::get('phone_cell'),                     'town_physical' => Input::get('town_physical'),                     'country_physical' => Input::get('country_physical'),                     'emergency_contact_1' => Input::get('emergency_contact_1'),                     'emergency_relationship_1' => Input::get('emergency_relationship_1'),                     'emergency_phone_1' => Input::get('emergency_phone_1'),                 ]);                      }            // get email from request         $email = $request->only('email');         foreach ($email as $userModel) {}          // Edit date of birth from request         $year = Input::get('year');         $month = Input::get('month');         $day = Input::get('day');                $dob = $year.'-'.$month.'-'.$day;         $data['dob'] = $dob;          // Attempt Registration         $result = $this->userRepository->store($data);                                  // Log user in         FunctionsController::loginUser($userModel);          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_complete', $result);     }      /**      * Activate a new user      *      * @param  int    $id      * @param  string $code      *      * @return Response      */     public function activate($hash, $code)     {         // Decode the hashid         $id = $this->hashids->decode($hash)[0];          // Attempt the activation         $result = $this->userRepository->activate($id, $code);          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_activated', $result);     }      /**      * Show the 'Resend Activation' form      *      * @return View      */     public function resendActivationForm()     {         return $this->viewFinder('Sentinel::users.resend');     }      /**      * Process resend activation request      * @return Response      */     public function resendActivation(EmailRequest $request)     {         // Resend the activation email         $result = $this->userRepository->resend(['email' => e($request->get('email'))]);          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_resend', $result);     }      /**      * Display the "Forgot Password" form      *      * @return \Illuminate\View\View      */     public function forgotPasswordForm()     {         return $this->viewFinder('Sentinel::users.forgot');     }       /**      * Process Forgot Password request      * @return Response      */     public function sendResetPasswordEmail(EmailRequest $request)     {         // Send Password Reset Email         $result = $this->userRepository->triggerPasswordReset(e($request->get('email')));          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_reset_triggered', $result);     }      /**      * A user is attempting to reset their password      *      * @param $id      * @param $code      *      * @return Redirect|View      */     public function passwordResetForm($hash, $code)     {         // Decode the hashid         $id = $this->hashids->decode($hash)[0];          // Validate Reset Code         $result = $this->userRepository->validateResetCode($id, $code);          if (! $result->isSuccessful()) {             return $this->redirectViaResponse('registration_reset_invalid', $result);         }          return $this->viewFinder('Sentinel::users.reset', [             'hash' => $hash,             'code' => $code         ]);     }      /**      * Process a password reset form submission      *      * @param $hash      * @param $code      * @return Response      */     public function resetPassword(ResetPasswordRequest $request, $hash, $code)     {         // Decode the hashid         $id = $this->hashids->decode($hash)[0];          // Gather input data         $data = $request->only('password', 'password_confirmation');          // Change the user's password         $result = $this->userRepository->resetPassword($id, $code, e($data['password']));          // It worked!  Use config to determine where we should go.         return $this->redirectViaResponse('registration_reset_complete', $result);     } } 
        
     
     

Lista de respuestas

0
 
vote

Parece que cuando hace clic y un enlace "Regístrese", su falla de redirección, así que verifique si tiene múltiples enlaces / botones "Registrarse", y si están apuntando a la URL derecha

¿Y para la depuración más fácil, debe hacer menos afirmaciones por prueba, obtendrá la visibilidad :)

 

It seems that when you click and a your link "Register" your redirection fail, so check if you have multiple "Register" links/buttons, and if they are pointing to the right URL

And for easiest debugging, you should make less assertions per Test, you will gain in visibility :)

 
 
     
     

Relacionados problema

1  phpunit dbunit @dataprovider no funciona  ( Phpunit dbunit dataprovider doesnt work ) 
Pasé mucho tiempo buscando dónde está el problema, pero no he encontrado nada. it sais "testadd causó un error: faltante argumento". Simplemente el DataProv...

10  Cobertura de código de agregación de diferentes marcos de prueba  ( Aggregating code coverage from different testing frameworks ) 
En el flujo de trabajo de programación moderno, se utilizan numerosos marcos de prueba a la vez. Por ejemplo, en PHP World, es una forma estándar de facto de ...

6  PHPUnit Falló el archivo requerido  ( Phpunit failed opening required file ) 
He navegado por problemas similares en adelante, pero en vano. Estoy ejecutando PHP 5.3.6 y PHPUnit versión 3.6.10. Al intentar ejecutar una prueba simple: ...

0  Phpunit Reporting "Aborted" sin importar las pruebas que se ejecuten  ( Phpunit reporting aborted no matter what tests are run ) 
Tener un problema raro con phpunit. Estamos usando phpunit como parte de un entorno de integración continua, que contiene una aplicación escrita usando Zend F...

6  Relaciones de Fábrica de Laravel ... Respeto Crear () o Hacer ()  ( Laravel factory relationships respect create or make ) 
Según Laravel's Documentación sobre la definición de las relaciones dentro de las fábricas del modelo : También puede adjuntar relaciones con los modelos ...

7  Formulario de Zend: ¿Cómo pasar parámetros al constructor?  ( Zend form how to pass parameters into the constructor ) 
Estoy tratando de probar mi forma. Se construirá otros objetos, así que necesito una manera de burlarse de ellos. Intenté pasarlos al constructor ... class...

2  ¿Cómo enviar la URL con subdominio en la prueba del controlador Zend Phpunit?  ( How to dispatch url with subdomain in zend phpunit controller test ) 
Quiero probar mi controlador que funciona en el subdominio www.username.domain.com El problema es cuando envío en el controlesto de control, tira zend_contr...

1  Zend Framework / phpunit: ¿Cómo Stub / Mofe un método de objeto que se conecta a una base de datos?  ( Zend framework phpunit how to stub mock an object method that connects to a dat ) 
En mi proyecto Marco Zend, tengo una forma que estoy probando. En mi forma, un elemento de selección múltiple obtiene sus opciones de un modelo, que las recup...

1  ¿Cómo conectar la base de datos de pruebas en las pruebas funcionales?  ( How to connect test database in functional testing ) 
Estudio una prueba funcional en Symfony y fue realmente exitoso trabajando en él, pero tengo problemas en la base de datos. En mi sistema, tengo 2 base de dat...

0  Cómo evitar que el módulo se cargue en Zend Framework 2 PHPUNIT PRUEBA  ( How to prevent module from being loaded in zend framework 2 phpunit test ) 
Escribí una aplicación ZF2 con un módulo de autenticación. La configuración de este módulo de autenticación se realiza en su archivo Module.php. Configuré u...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos