Laravel -Test перенаправляет на страницу входа вместо ожидаемой темы - PullRequest
1 голос
/ 19 октября 2019

Я подписан на это Laracasts видео. Я создал тест, который должен обеспечить отправку новой ветки форума. То, что происходит сейчас, когда я звоню $this->get($thread->path()) с помощью PHPUnit, тест перенаправляет на страницу входа. Забавно, однако, что я даже не установил промежуточное программное обеспечение или что-то еще, и я вошел в систему, поэтому я не знаю, почему тест перенаправляет. Когда я захожу в ветку в браузере, однако. все работает нормально.

Вот мой код;

CreateThreadTest.php

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class CreateThreadsTest extends TestCase
{

    use DatabaseMigrations;

    function test_an_authenticated_user_can_create_new_forum_threads() {
        $this->ActingAs(factory('App\User')->create());

        $thread = factory('App\Thread')->make();

        $this->post('/forum/threads', $thread->toArray());

        $this->get($thread->path())->assertSee($thread->title)->assertSee($thread->body);


    }
}

ThreadsControkller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Thread;
class ThreadsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $threads = Thread::latest()->get();
        return view('threads.index', compact('threads'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $thread = Thread::create([
            'user_id' => auth()->id,
            'title' => request('title'),
            'body' => request('body')
        ]);

       return redirect($thread->path());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Thread $thread)
    {
        return view('threads.show', compact('thread'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

Thread.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    protected $guarded = [];
    public function path() {
        return "/forum/threads/" . $this->id;
    }

    public function replies() {
        return $this->hasMany(Reply::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function addReply($reply) {
        $this->replies()->create($reply);
    }
}

Есть идеи, почему это происходит? РЕДАКТИРОВАТЬ здесь это ошибка


Time: 866 ms, Memory: 26.00 MB

There was 1 failure:

1) Tests\Feature\CreateThreadsTest::test_an_authenticated_user_can_create_new_forum_threads
Failed asserting that '<!DOCTYPE html>\n
<html lang="en">\n
<head>\n
    <meta charset="utf-8">\n
    <meta name="viewport" content="width=device-width, initial-scale=1">\n
\n
    <!-- CSRF Token -->\n
    <meta name="csrf-token" content="aVe2XAPPH8ZUdPONN1Teqg1Wb7fgE7cPqhfSwl9E">\n
\n
    <title>Laravel</title>\n
\n
    <!-- Scripts -->\n
    <script src="http://localhost/js/app.js" defer></script>\n
\n
    <!-- Fonts -->\n
    <link rel="dns-prefetch" href="//fonts.gstatic.com">\n
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">\n
\n
    <!-- Styles -->\n
    <link href="http://localhost/css/app.css" rel="stylesheet">\n
</head>\n
<body style="padding-bottom:100px">\n
    <div id="app">\n
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">\n
            <div class="container">\n
                <a class="navbar-brand" href="http://localhost">\n
                    Laravel\n
                </a>\n
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">\n
                    <span class="navbar-toggler-icon"></span>\n
                </button>\n
\n
                <div class="collapse navbar-collapse" id="navbarSupportedContent">\n
                    <!-- Left Side Of Navbar -->\n
                    <ul class="navbar-nav mr-auto">\n
                        <li><a href="/forum/threads">All threads</a></li>\n
                        <li></li>\n
                    </ul>\n
\n
                    <!-- Right Side Of Navbar -->\n
                    <ul class="navbar-nav ml-auto">\n
                        <!-- Authentication Links -->\n
                                                    <li class="nav-item dropdown">\n
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>\n
                                    Mr. Magnus Fay III <span class="caret"></span>\n
                                </a>\n
\n
                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">\n
                                    <a class="dropdown-item" href="http://localhost/logout"\n
                                       onclick="event.preventDefault();\n
                                                     document.getElementById('logout-form').submit();">\n
                                        Logout\n
                                    </a>\n
\n
                                    <form id="logout-form" action="http://localhost/logout" method="POST" style="display: none;">\n
                                        <input type="hidden" name="_token" value="aVe2XAPPH8ZUdPONN1Teqg1Wb7fgE7cPqhfSwl9E">                                    </form>\n
                                </div>\n
                            </li>\n
                                            </ul>\n
                </div>\n
            </div>\n
        </nav>\n
\n
        <main class="py-4">\n
                <div class="container">\n
        <div class="row justify-content-center">\n
            <div class="col-md-8">\n
                <div class="card">\n
                    <div class="card-header">Forum threads</div>\n
\n
                    <div class="card-body">\n
                        \n
\n
                        You are logged in!\n
                    </div>\n
                </div>\n
            </div>\n
        </div>\n
    </div>\n
        </main>\n
    </div>\n
</body>\n
</html>\n
' contains "Ut neque nam maxime facilis sunt et.".

/home/vagrant/Code/intransportal/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:363
/home/vagrant/Code/intransportal/tests/Feature/CreateThreadsTest.php:22
/home/vagrant/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:200
/home/vagrant/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:159

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Ответы [ 2 ]

0 голосов
/ 19 октября 2019

Некоторое время назад я следовал той же серии и прошел тот же тест здесь

Создать функцию входа в систему в TestCase классе, таком как этот здесь

protected function login($user = null)
{
  $user = $user ?: factory('App\User')->create();
  $this->be($user);
  return $this;
}

И используйте его в тесте примерно так:

Нажмите URL-адрес ответа, а не несуществующую ветку

public function test_users_can_create_statuses()
{
  $this->login();
  $thread = factory('App\Thread')->make();
  $response = $this->post('/forum/threads', $thread->toArray());
  $this->get($response->headers->get('Location'))
             ->assertSee($thread->title);
             ->assertSee($thread->body);
}

Вы можете найти еще несколько интересных настроекчто GitHub Repo

Надеюсь, это поможет

0 голосов
/ 19 октября 2019

Вы забыли вернуть вставленную нить в свой метод тестирования, поэтому она должна выглядеть следующим образом:

 function test_an_authenticated_user_can_create_new_forum_threads() {
        $this->ActingAs(factory('App\User')->create());

        $thread = factory('App\Thread')->make();

        $this->post('/forum/threads', $thread->toArray());

        // you are missing this line

        $threadFromDb = Thread::where($thread->toArray())->first();

        $this->get($threadFromDb->path())->assertSee($thread->title)->assertSee($thread->body);


    }

, поскольку в своем утверждении вы использовали $thread->path(), а в методе path() вынужен идентификатор, который не является выходом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...