【问题标题】:Laravel testing Failed asserting that two strings are equalLaravel测试失败断言两个字符串相等
【发布时间】:2017-11-03 16:31:37
【问题描述】:

我对测试非常陌生,但现在发现自动化测试至关重要。

我有一个测试工作正常,直到它到达链接“/cart”它到达链接“/cart”没问题,但我之后尝试点击的任何其他链接总是最终回到购物车.

这是我尝试离开购物车后的错误。

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

这是我的测试脚本

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');             
    }

}

在此评论之前一切正常

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

这是我的注册控制器

<?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);
    }
}

【问题讨论】:

  • 请向我们展示您处理注册表单提交的控制器方法。
  • 谢谢。我已经添加了控制器。函数是public function register(RegisterRequest $request)
  • 你能显示$this-&gt;redirectViaResponse方法吗?

标签: laravel testing phpunit


【解决方案1】:

似乎当您单击“注册”链接时,您的重定向失败,因此请检查您是否有多个“注册”链接/按钮,以及它们是否指向正确的 URL

为了最简单的调试,您应该减少每次测试的断言,您将获得可见性:)

【讨论】:

  • 您好,感谢您的回复。注册似乎可以工作,因为数据库会使用用户详细信息进行更新,然后重定向到购物车。重定向到购物车有问题吗?
  • 填写表格后手动点击注册时,您的表格是否提交到 /cart 页面?或者你有一个中间页面?
  • 不,没有中间页。它进行注册然后路由到购物车。
猜你喜欢
  • 2020-01-08
  • 2021-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多