sublime text 中需通过 build system 定义 test variant 并在 user.sublime-keymap 中配置 {"keys": ["ctrl+t"], "command": "build", "args": {"variant": "test"}, "context": [{"key": "selector", "operator": "equal", "operand": "source.rust"}]},同时确保 build system 设置 "working_dir": "${project_path:${folder}}" 且以文件夹方式打开项目,否则 context 不匹配或 cargo test 执行失败。

Sublime Text 里没有“运行测试”的内置快捷键,必须靠 Build System + 自定义 key binding 组合实现;直接抄网上旧配置大概率 Ctrl+T 按下没反应,核心卡点是 command 名不匹配、context 不生效、或 cargo test 在错误目录执行。
怎么让 Ctrl+T 真正触发 cargo test
Sublime 不认识 cargo test 这个命令,它只认你 Build System 里定义的 variant 名。所以不能只写 command: build,必须带 args 指定变体。
- 先确认你已建好 Build System(如
Rust.sublime-build),里面包含名为Test的variant,内容类似:{ "name": "Test", "shell_cmd": "cargo test" } - 在
User.sublime-keymap里加这条规则(不是覆盖默认键,而是新增):[{ "keys": ["ctrl+t"], "command": "build", "args": {"variant": "Test"}, "context": [ {"key": "selector", "operator": "equal", "operand": "source.rust"} ] }] - 务必检查右下角状态栏显示的是
Rust,不是Plain Text——否则context不匹配,按键静默失效
为什么 cargo test 找不到 Cargo.toml 或报错 no targets
Build System 默认在 ${file_path} 下执行,而 cargo test 必须在含 Cargo.toml 的项目根目录跑,否则直接失败。
- 你的
Rust.sublime-build必须显式指定"working_dir": "${project_path:${folder}}",不能省略 - 打开项目时,用
File → Open Folder加载整个文件夹(确保侧边栏能看到Cargo.toml),别只双击src/lib.rs单文件 - 按
Ctrl+`打开控制台,执行import os; print(os.getcwd()),确认当前工作目录确实是项目根目录
如何区分“运行”和“测试”,避免快捷键冲突
很多人把 Ctrl+B 改成 cargo run,又想用 Ctrl+T 做 cargo test,但没加 context 就容易误触——比如在 Markdown 文件里按 Ctrl+T,Sublime 会尝试构建,然后报一堆无关错误。
- 推荐给不同操作配不同 context:
–cargo run限定"operand": "source.rust"+"match_all": true
–cargo test额外加一条{"key": "setting.is_test_file", "operator": "equal", "operand": true}(需配合插件或手动设文件属性) - 更稳妥的做法:把测试命令绑定到
Ctrl+Shift+T,避开所有默认键冲突 - 如果用
LSP-rust-analyzer,它自带lsp_rust_analyzer_run_test命令,但这个 command 名必须实测获取(Ctrl+Shift+P搜 “run test” 看真实名),不能硬写
单文件测试?别用 cargo test
如果你只是临时写个 hello.rs 想快速验证逻辑,cargo test 会直接报错:no Cargo.toml file found。这不是配置问题,是设计如此。
- 这种场景改用
rustc编译单文件:"shell_cmd": "rustc $file_name -o ${file_base_name} && ./${file_base_name}" - 或者干脆不配快捷键,终端里敲
rustc hello.rs && ./hello更快 - 真要测试单文件逻辑,用
#[cfg(test)]写在文件末尾,再通过cargo test --lib跑——但这要求你至少有个最小Cargo.toml
最常被忽略的一点:Build System 里 "shell_cmd" 和 "cmd" 行为完全不同。shell_cmd 走系统 shell,能展开 $file_name、继承 PATH;cmd 直接调进程,在 Windows 上遇到空格路径几乎必崩。别图省事漏掉 s。











