TDD 构建 Laravel 应用之任务UI更新

本系列文章为 laracasts.com 的系列视频教程 ——Build A Laravel App With TDD 的学习笔记,若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版

  • 任务添加权限测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/** @test */
public function guests_cannot_add_tasks_to_project()
{
$project = factory(Project::class)->create();
$this->post($project->path() . '/tasks')->assertRedirect('login');
}

/** @test */
public function only_the_owner_of_a_project_may_add_tasks()
{
$this->signIn();
$project = factory(Project::class)->create();
$this->post($project->path() . '/tasks',
['body' => 'Test task'])->assertStatus(403);

$this->assertDatabaseMissing('tasks', ['body' => 'Test task']);
}

测试结果:

Tests\Feature\ProjectTasksTest::only_the_owner_of_a_project_may_add_tasks
Expected status code 403 but received 302.
Failed asserting that false is true.

在控制器中增加权限控制:

1
2
3
4
5
6
7
8
9
10
public function store(Project $project)
{
if (auth()->user()->isNot($project->owner)) {
abort(403);
}
request()->validate(['body'=> 'required']);
$project->addTask(request('body'));

return redirect($project->path());
}

测试通过!