iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 16
0
Software Development

如何一步步實踐TDD (測試驅動開發)系列 第 16

TDD 實戰 D2:Laravel 資料庫 (1)

今天要來做一個新的頁面,是用來顯示使用者發過的所有文章,而文章會被記錄在資料庫內。


Post 路由

原本只有首頁的路由 /,所以要來寫一個新的 /posts/ 路由,同樣也是從測試開始。

紅燈

$ php artisan make:test PostTest
// tests/PostTest.php
class PostTest extends TestCase
{
    /**
     * @return void
     */
    public function testAllPost()
    {
        $response = $this->get('/posts/');
        $response->assertStatus(200);
        $response->assertSee('All Posts:');
    }
}

綠燈

新增路由。

// routes/web.php
Route::get('/posts/', function () {
    return 'All Posts:';
});

資料庫

這邊不得已,要先違反 TDD 的作法,學習 Laravel 資料庫的語法花了一點時間,因此今天先手動建置一些資料。

.env

先修改 .env 的設定值,Laravel 預設是用 MySQL,但我們選擇輕量的 sqlite 來用。

原本的 Database 設定是這段:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
...

改成只要一行。

DB_CONNECTION=sqlite

SQLite

sqlite 預設在 MacOS 中本來就有裝,可以用 sqlite3 的指令來創建一個資料庫。

$ sqlite3 database/database.sqlite

就目前所知,Laravel 預設抓取 sqlite 的檔案路徑是 database/database.sqlite,同時該資料夾底下也有寫好的 .gitignore 來指示 Git 忽略他們。

Model

Artisan 提供了指令來產生程式檔案:

$ php artisan make:model Post -mf

-m 參數會同時創造等等用來 Migrate 的檔案。

Model 產生在 app/Post.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

Migrate

資料表會隨著系統更新而變化,Migrate 就是用來編寫每一次資料表改變的內容。

剛剛自動產生的 Migrate 檔案在 database/migrations 中,除了預設的部分,還要再加入新的 post_text 欄位。

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('post_text'); // 我們新增的
    $table->timestamps();
});

接著下 migrate 指令,就會在 database/database.sqlite 資料庫中增加新的資料表。

$ php artisan migrate

手動新增資料

這邊先手動新增一筆資料在裡面,之後再來改成自動產生,使用 sqlite 的 shell 模式。

$ sqlite3 database/database.sqlite
$ INSERT INTO posts (post_text) VALUES ("Hello, I'm Louis.");

測試資料庫中有這筆資料

class PostTest extends TestCase
{
    public function testInsertPost()
    {
        $this->assertDatabaseHas('posts', [
            'post_text' => "Hello, I'm Louis."
        ]);
    }
}

assertDatabaseHas() 第一個參數是 table 的名稱,而第二個參數的陣列則是要確認的資料,key 是欄位名稱。

修改 Post 頁面,印出所有文章

紅燈

class PostTest extends TestCase
{
    /**
     * @return void
     */
    public function testAllPost()
    {
        $response = $this->get('/posts/');
        $response->assertStatus(200);
        $response->assertSee('All Posts:');

        $response->assertSee("Hello, I'm Louis."); //目前的文章
    }

綠燈

Route::get('/posts/', function () {
    $response = "All Posts: ";
    $posts = Post::all();
    foreach ($posts as $post) {
        $response .= $post;
    }
    return $response;
});

現在我們的 /posts/ 頁面,會顯示 All Posts: {"id":3,"post_text":"Hello, I'm Louis.","created_at":null,"updated_at":null} 的字樣。

關於資料庫,讓我們明天接力。


上一篇
Laravel:消失的 visit() 函式
下一篇
TDD 實戰 D3:Laravel 資料庫 (2)
系列文
如何一步步實踐TDD (測試驅動開發)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言