你的第一个问题:
...我看到的用于 Serverspec 的所有教程都应该而不是期望。这是因为 Serverspec 没有更新为使用期望吗?
不,这主要是因为 Serverspec 项目的作者偏爱“应该”语法,这就是 Serverspec 文档继续使用它的原因。他在这里解释说:
我使用should
语法而不是expect
语法,因为我认为should
语法比expect
语法更具可读性并且我喜欢它。
推荐使用expect
语法,因为should
在与 BasicObject 子类代理对象一起使用时,添加到每个对象都会导致失败。
但是本页示例中使用的单行语法不会将 should 添加到任何对象,因此这种语法不会导致上述问题。这就是我使用单行应该语法的原因。
请注意,should
来自expect
rspec -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
也可以看看: