Menu

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

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

本文章首发在 Laravel China 社区
上一篇 下一篇
讨论数量: 0
发起讨论


暂无话题~
刻意练习,每日精进。
2
点赞
170
浏览
0
讨论

维护者
14
14