PHPUnit всегда берет меня на страницу входа. независимо от того, что я делаю - PullRequest
1 голос
/ 19 октября 2019

Так что у меня возникла небольшая интересная проблема. Я пытаюсь создать форум для моего сайта. Я пытаюсь создать тест, который гарантирует, что зарегистрированные пользователи могут отправлять новые темы на форуме. Теперь, независимо от того, что я делаю, тест всегда заканчивается на странице входа в систему, даже если я вошел в систему.

Однако, вот что-то интересное, когда я пытаюсь dd() поток сразу после созданияПохоже, что Laravel «пропустил» команду dd, и я получаю сообщение об ошибке «Заголовок темы не найден на странице входа». Я могу dd() объект $request, и это распечатывается нормально, однако, после создания новой модели потока Laravel пропускает команду dd($thread), и в итоге я получаю страницу входа еще раз.

Я вырываю волосы. Почему это происходит?

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use App\Thread;
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->be(factory('App\User')->create());

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

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

            // you are missing this line
            $this->get($thread->path())->assertSee($thread->title)->assertSee($thread->body);


        }



}
<?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)
    {
        //
    }
}

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

1 Ответ

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

Когда вы make новой модели используете помощник factory, у нее нет идентификатора

, например

enter image description here

Итак, $thread->path() вернет просто "/forum/threads/", что не то, что вы хотите

Вы должны сделать запрос к местоположению из ответа или запросить вновь созданную запись потока

public function test_users_can_create_statuses()
{
  $this->be(factory('App\User')->create());
  $thread = factory('App\Thread')->make();
  $response = $this->post('/forum/threads', $thread->toArray());
  $this->get($response->headers->get('Location'))
             ->assertSee($thread->title);
             ->assertSee($thread->body);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...