0

给定最小的例子

# 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”

确保即使由于某种原因更改了正则表达式,名称属性仍然可以正常工作。

我浏览了几本顶级厨师食谱,但找不到此类测试的参考资料。

怎么做到呢?Chef::Resource如果这有助于完成任务,请随意提供具有显式子类化的更复杂示例。

更新 1:当属性不适合时,厨师不会失败regex吗?显然这不应该工作:

link '/none' do
  owner  'r<oo=t'
  to     '/usr'
end

但是chef-apply(12.13.37) 并没有抱怨r<oo=tnot matching owner_valid_regex。它只是收敛,好像owner没有提供一样。

4

2 回答 2

2

您将使用 ChefSpec 和 RSpec。我的所有食谱中都有示例(例如https://github.com/poise/poise-python/tree/master/test/spec/resources),但我还使用了一堆自定义助手ChefSpec 所以它可能不是很有帮助。在规范中执行内联配方代码块使其更容易。我已经开始在https://github.com/poise/poise-spec中提取我的助手以供外部使用,但它还没有完成。当前的助手在我的 Halite gem 中,请参阅那里的自述文件以获取更多信息。

于 2016-09-16T08:11:26.013 回答
0

我们将 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
于 2016-09-18T21:10:34.363 回答