91.更新话题(一)

未匹配的标注

本节说明

  • 对应视频教程第 91 小节:A Thread Can Be Updated

本节内容

下面我们进行话题更新功能的开发。我们设定只有话题的创建者才能更新允许更新,且只能更新titlebody字段,并且更新的内容要符合我们设定的验证规则。因为,我们来添加 3 个测试:
forum\tests\Feature\UpdateThreadsTest.php

<?php

namespace Tests\Feature;

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

class UpdateThreadsTest extends TestCase
{
    use RefreshDatabase;

    public function setUp()
    {
        parent::setUp();
        // 每个测试都需要用到以下操作
        $this->withExceptionHandling();

        $this->signIn();
    }

    /** @test */
    public function unauthorized_users_may_not_update_threads() // 只有话题创建者才能更新
    {
        $thread = create('App\Thread',['user_id' => create('App\User')->id]);

        $this->patch($thread->path(),[])->assertStatus(403);
    }

    /** @test */
    public function a_thread_requires_a_title_and_body_to_be_updated() // 更新的字段要符合规则
    {
        $thread = create('App\Thread',['user_id' => auth()->id()]);

        $this->patch($thread->path(),[
            'title' => 'Changed.'
        ])->assertSessionHasErrors('body');

        $this->patch($thread->path(),[
            'body' => 'Changed.'
        ])->assertSessionHasErrors('title');
    }

    /** @test */
    public function a_thread_can_be_updated_by_its_creator() // 话题可以成功更新
    {
        $thread = create('App\Thread',['user_id' => auth()->id()]);

        $this->patch($thread->path(),[
            'title' => 'Changed.',
            'body' => 'Changed body.'
        ]);

        tap($thread->fresh(),function ($thread) {
            $this->assertEquals('Changed.',$thread->title);
            $this->assertEquals('Changed body.',$thread->body);
        });
    }
}

添加更新路由:
forum\routes\web.php

.
Route::get('threads/{channel}/{thread}','ThreadsController@show');
Route::patch('threads/{channel}/{thread}','ThreadsController@update');
.

修改控制器:
forum\app\Http\Controllers\ThreadsController.php

    .
    .
    public function update($channelId,Thread $thread)
    {
        // 应用授权策略
        $this->authorize('update',$thread);
        // 验证规则
        $thread->update(request()->validate([
            'title' => 'required|spamfree',
            'body' => 'required|spamfree'
        ]));

        return $thread;
    }
    .
    .

运行测试:
file

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~