41.话题订阅(二)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 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');
.
.
运行测试:
接下来新建控制器:
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');
.
.
再次测试:
接下里我们需要修改测试:
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);
}
}
再次测试:
我们的测试通过了,但是非常的粗略。我们设想的订阅功能应该是订阅了某个话题,当话题有新回复时,我们通知订阅该话题的用户。所以我们来修改测试:
<?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);
}
}
下一节我们继续话题订阅的功能。