0

我听说我应该在 Serverspec 中使用期望而不是“应该”陈述

我一直在谷歌搜索可用于文件匹配的期望,但我看到的用于 Serverspec 的所有教程都应该而不是期望。这是因为 Serverspec 没有更新为使用期望吗?

describe file('/etc/yum.conf') do
  it { should be_file }
  it { should be_owned_by 'root' }
  it { should be_grouped_into 'root' }
  it { should be_mode 644 }

  its(:content) { should match /^gpgcheck=1$/ }
  its(:content) { should match /^clean_requirements_on_remove=1$/ }
end

那么我将如何使用期望而不是应该编写测试呢?

4

1 回答 1

1

你的第一个问题:

...我看到的用于 Serverspec 的所有教程都应该而不是期望。这是因为 Serverspec 没有更新为使用期望吗?

不,这主要是因为 Serverspec 项目的作者偏爱“应该”语法,这就是 Serverspec 文档继续使用它的原因。他在这里解释说:

我使用should语法而不是expect语法,因为我认为should语法比expect语法更具可读性并且我喜欢它。

推荐使用expect语法,因为should在与 BasicObject 子类代理对象一起使用时,添加到每个对象都会导致失败。

但是本页示例中使用的单行语法不会将 should 添加到任何对象,因此这种语法不会导致上述问题。这就是我使用单行应该语法的原因。

请注意,should来自expectrspec -expectations项目,Serverspec 作者是正确的“应该”而不是“期望”,他使用它的方式很好。

这里有更多关于期望语法的原始动机的信息来自 Rspec 作者 Myron Marston 。

你的第二个问题:

...我将如何使用期望而不是应该编写测试?

如果您仍想使用该expect语法,只需将should到处替换为is_expected.to到处。这工作正常:

describe file("/etc/passwd") do
  it { is_expected.to be_file }
  its(:content) { is_expected.to match /root/ }
end

你也可以这样写:

describe "passwd file" do
  it "the passwd file should be a file" do
    expect(file("/etc/passwd")).to be_file }
  end
  it "and it should contain root" do
    expect(file("/etc/passwd").content).to match /root/
  end
end

甚至:

describe file("/etc/passwd") do
  it { expect(subject).to be_file }
  it { expect(subject.content).to match /root/ }
end

也可以看看:

于 2019-05-22T10:54:58.637 回答