41.话题订阅(二)

未匹配的标注

本节说明

  • 对应视频教程第 41 小节:Thread Subscriptions(Part 2)

本节内容

上一节我们完成了订阅功能的单元测试,这一节我们将完成订阅功能的功能测试。首先新建测试文件:
forum\tests\Feature\SubscribeToThreadsTest.php

<?php

namespace Tests\Feature;

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

class SubscribeToThreadsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function a_user_can_subscribe_to_threads()
    {
        $thread = create('App\Thread');

        $this->post($thread->path() . '/subscriptions');

        $this->assertCount(1,$thread->subscriptions);
    }
}

我们添加了第一个功能测试,但是我们还需要添加路由:
forum\routes\web.php

.
.
Route::delete('/replies/{reply}/favorites','FavoritesController@destroy');
Route::post('/threads/{channel}/{thread}/subscriptions','ThreadSubscriptionsController@store');
.
.

运行测试:
file
接下来新建控制器:
forum\app\Http\Controllers\ThreadSubscriptionsController.php

<?php

namespace App\Http\Controllers;

use App\Thread;

class ThreadSubscriptionsController extends Controller
{
    public function store($channelId,Thread $thread)
    {
        $thread->subscribe();
    }
}

我们还需要为我们的控制器加上Auth中间件,用以过滤掉未登录用户:
forum\routes\web.php

.
Route::post('/threads/{channel}/{thread}/subscriptions','ThreadSubscriptionsController@store')->middleware('auth');
.
.

再次测试:
file
接下里我们需要修改测试:
forum\tests\Feature\SubscribeToThreadsTest.php

<?php

namespace Tests\Feature;

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

class SubscribeToThreadsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function a_user_can_subscribe_to_threads()
    {
        $this->signIn();

        $thread = create('App\Thread');

        $this->post($thread->path() . '/subscriptions');

        $this->assertCount(1,$thread->subscriptions);
    }
}

再次测试:
file
我们的测试通过了,但是非常的粗略。我们设想的订阅功能应该是订阅了某个话题,当话题有新回复时,我们通知订阅该话题的用户。所以我们来修改测试:

<?php

namespace Tests\Feature;

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

class SubscribeToThreadsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function a_user_can_subscribe_to_threads()
    {
        $this->signIn();

        // Given we have a thread
        $thread = create('App\Thread');

        // And the user subscribes to the thread
        $this->post($thread->path() . '/subscriptions');

        // Then,each time a new reply is left...
        $thread->addReply([
           'user_id' => auth()->id(),
           'body' => 'Some reply here' 
        ]);

        // A notification should be prepared for the user.
        $this->assertCount(1,auth()->user()->notifications);
    }
}

下一节我们继续话题订阅的功能。

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

上一篇 下一篇
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~