我有一本安装“git version 2.5.2”的厨师食谱。我正在使用 CentOS 6.4 vm 来应用这本食谱并编写了一个测试来检查 git 版本。
片段如下所示:
# Test if git exists
describe command('git --version') do
its(:stdout) { should match "git version 2.5.2" }
end
当我运行 kitchen verify 时,测试已执行,但返回的 git 版本与我预期的不同,这会导致测试失败。
这是错误:
2) Command "git --version" stdout should match "git version 2.5.2"
Failure/Error: its(:stdout) { should match "git version 2.5.2" }
expected "git version 1.7.1\n" to match "git version 2.5.2"
Diff:
@@ -1,2 +1,2 @@
-git version 2.5.2
+git version 1.7.1
/bin/sh -c git\ --version
git version 1.7.1
VM 恰好在 /usr/bin 目录中安装了 git 版本 1.7.1。该配方将 git 版本 2.5.2 安装在 /usr/local/bin 目录中。当我使用“厨房登录”命令登录到 VM 时,我以 vagrant 用户身份连接。/usr/local/bin 目录在 PATH 中比 /usr/bin 高,所以当我运行“git --version”时,我会得到“git version 2.5.2”作为我的输出。但是,当我运行 kitchen verify 时,它将使用 root 用户执行我的测试。root 用户的 PATH 不包括 /usr/local/bin,但确实有 /usr/bin,因此它返回“git version 1.7.1”。
在执行测试时,如何控制厨房验证将使用的 VM 上的哪个用户?
我尝试在这样的测试中使用“su -c”命令:
describe command('su -c "whoami" vagrant') do
its(:stdout) { should match "vagrant" }
end
结果如预期:
Command "su -c "whoami" vagrant"
stdout
should match "vagrant"
使用 git 命令进行更改:
describe command('su -c "git --version" vagrant') do
its(:stdout) { should match "git version 2.5.2" }
end
结果:
1) Command "su -c "git --version" vagrant" stdout should match "git version 2.5.2"
Failure/Error: its(:stdout) { should match "git version 2.5.2" }
expected "" to match "git version 2.5.2"
/bin/sh -c su\ -c\ \"git\ --version\"\ vagrant
检查 vagrant 用户的路径:
describe command('su -c "echo $PATH" vagrant') do
its(:stdout) { should match "" }
end
在这种情况下测试成功。没有为 vagrant 用户设置路径,因此普通的“git --version”命令将不起作用。