给出最小的例子
# resources/novowel.rb
resource_name :novowel
property :name, String, name_property: true, regex: /A[^aeiou]z/
我想在spec/unit/resources/novowel_spec.rb
中编写单元测试
- 资源名称'novowel'应该接受'k'
- 资源名称'novowel'应该接受'&'
- 资源名称'novowel'不应该接受'a'
- 资源名称'novowel'不应该接受'mm'
确保即使regex由于某种原因改变了,name属性仍然可以正常工作。
我浏览了几本顶级厨师的烹饪书,但没有找到这种测试的参考资料。
怎么做呢?如果对Chef::Resource
显式子类化有助于完成任务,请随意提供更复杂的示例。
更新1:可能是厨师不失败时,一个属性不适合regex
?显然这是行不通的:
link '/none' do
owner 'r<oo=t'
to '/usr'
end
但chef-apply
(12.13.37)不抱怨r<oo=t
不匹配owner_valid_regex
。它只是简单地收敛,就好像没有提供owner
一样。
您将使用ChefSpec和RSpec。我在所有的烹饪书中都有例子(例如https://github.com/poise/poise-python/tree/master/test/spec/resources),但我也使用了一堆自定义助手,所以它可能不是特别有用。在规范中使用内联配方代码块会让它变得更容易。我已经开始提取我的助手在https://github.com/poise/poise-spec外部使用,但它还没有完成。当前的帮助程序在我的Halite gem中,更多信息请参阅此处的自述文件
我们将DSL封装在一小段Ruby代码中,以便知道资源的Ruby类的名称:
# libraries/no_vowel_resource.rb
require 'chef/resource'
class Chef
class Resource
class NoVowel < Chef::Resource
resource_name :novowel
property :letter, String, name_property: true, regex: /A[^aeiou]z/
property :author, String, regex: /A[^aeiou]+z/
end
end
end
,现在我们可以在RSpec中使用
# spec/unit/libraries/no_vowel_resource_spec.rb
require 'spec_helper'
require_relative '../../../libraries/no_vowel_resource.rb'
describe Chef::Resource::NoVowel do
before(:each) do
@resource = described_class.new('k')
end
describe "property 'letter'" do
it "should accept the letter 'k'" do
@resource.letter = 'k'
expect(@resource.letter).to eq('k')
end
it "should accept the character '&'" do
@resource.letter = '&'
expect(@resource.letter).to eq('&')
end
it "should NOT accept the vowel 'a'" do
expect { @resource.letter = 'a' }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "should NOT accept the word 'mm'" do
expect { @resource.letter = 'mm' }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
describe "property 'author'" do
it "should accept a String without vowels" do
@resource.author = 'cdrngr'
expect(@resource.author).to eq('cdrngr')
end
it "should NOT accept a String with vowels" do
expect { @resource.author = 'coderanger' }.to raise_error(Chef::Exceptions::ValidationFailed)
end
end
end