不占用端口来测试笔记路由

用

发布这门课仍然是 0.x 测试版。某个测试助手消失了,去看你这个 crate 的测试指南,而不是同名的 PHPUnit 方法。

带 Application 参数的 #[laravel::test] 会让请求走过中间件、路由和处理器。它不占用端口。测试里不应该请求 127.0.0.1:8000。每个测试有自己的应用,Cargo 会并行运行测试。

src/testing.rs 就是这个应用使用的配置。for_testing 把 APP_ENV 设为 testing,并应用该文件里的覆盖,其中包括 QUEUE_CONNECTION=sync、MAIL_MAILER=log 和 refresh_database()。同步队列会在测试进程里运行任务。log 邮件器把消息写下来,而不是发出去。refresh_database 给测试一张它自己的、已经迁移过的库。目录结构指南说,起步应用的测试需要 PostgreSQL 才能这样刷新。把 DATABASE_URL 指向一个你可以清空的库。

访客和空白标题

form 像浏览器一样提交。验证失败会重定向回去。json 会带上 Accept: application/json,所以同样的非法请求体是 422。assert_unprocessable 就是这个状态。assert_invalid 对 JSON 响应和闪存进会话的 Web 错误都能检查字段。

use laravel::testing::prelude::*;

use app::models::User;

#[laravel::test]
async fn guests_cannot_store_notes(app: Application) {
    app.post("/notes")
        .form([("title", "")])
        .await
        .assert_redirect();
}

#[laravel::test]
async fn blank_titles_are_422_for_json(app: Application) -> laravel::Result<()> {
    let user = User::factory().create().await?;

    app.post("/notes")
        .acting_as(&user)
        .json(json!({ "title": "", "body": "A note" }))
        .await
        .assert_unprocessable()
        .assert_invalid(&["title"]);

    Ok(())
}

User::factory().create() 是模型指南在测试里播种用户的方式。acting_as 出现在同一指南的删除示例里。如果起步应用的 User 还没有工厂,模型指南也给出了 create!(User { name: "Taylor", email: "taylor@example.com", password: "secret" }),它会替你哈希这个字符串。用这两种之一。不要发明第三种构造方式。

访客断言用 assert_redirect,是因为 Authenticate 或 #[validate(authenticated)] 会把浏览器客户端送到登录页。它并不断言笔记已经保存。接着写一个登录后检查这一行的测试:

#[laravel::test]
async fn authors_can_store_notes(app: Application) -> laravel::Result<()> {
    let user = User::factory().create().await?;

    app.post("/notes")
        .acting_as(&user)
        .from("/notes")
        .form([
            ("title", "Read the migration"),
            ("body", "The table is in the binary."),
        ])
        .await
        .assert_redirect();

    app.assert_database_has("notes", json!({
        "user_id": user.id,
        "title": "Read the migration",
    })).await;

    Ok(())
}

from 设置 Referer 头。当你要的是验证错误本身时,assert_redirect_back_with_errors 更严格。测试指南在 from 之后使用它。如果单独的 assert_redirect 太容易被登录重定向满足,就在浏览器提交空白标题的用例上改用它。

按名字跑一部分:

cargo test notes

cargo nextest run 也可以。没有 Application 参数的测试不会启动应用。那些留给纯函数。笔记路由不是纯函数。

检验一下

笔记的 store 路由还不存在时,cargo test notes 失败;访客被重定向、空白 JSON 标题返回 422 之后,它应该通过。

返回路线图