如何控制哪个用户"厨房验证"在测试命令资源时使用?

时间:2015-10-28 17:47:59

标签: chef serverspec

我有一个厨师食谱,安装" git版本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

当我运行厨房验证时,测试执行但返回的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版。配方在/ usr / local / bin目录中安装git版本2.5.2。当我使用命令" kitchen login"登录VM时,我作为流浪者用户连接。 / usr / local / bin目录在PATH中比/ usr / bin高,所以当我运行" git --version"时,我会得到" git版本2.5.2& #34;作为我的输出。当我运行厨房验证时,它将与root用户一起执行我的测试。 root用户的PATH不包含/ usr / local / bin,但确实有/ usr / bin所以它返回" git版本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

检查流浪者用户的路径:

describe command('su -c "echo $PATH" vagrant') do
  its(:stdout) { should match "" }
end

在这种情况下,测试成功。没有为流浪者用户设置路径,所以简单的" git --version"命令不起作用。

1 个答案:

答案 0 :(得分:0)

Since the -c switch worked to change the user, I looked up the man page for su to see what other switches I could try. The -l or --login switch looked promising. describe command('su -c --login "git --version" vagrant') do its(:stdout) { should match "git version 2.5.2" } end The test still fails... 1) Command "su -c --login "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\ --login\ \"git\ --version\"\ vagrant Looking at the order of the switches though... describe command('su --login -c "git --version" vagrant') do its(:stdout) { should match "git version 2.5.2" } end The test succeeds. I didn't think the order of the switches would influence the outcome, but it does. Thanks to Draco Ater for the helpful comments.