如何为自定义 Chef 资源编写回归测试?

How to write regression tests for custom Chef resources?

给出最小的例子

# resources/novowel.rb
resource_name :novowel
property :name, String, name_property: true, regex: /\A[^aeiou]\z/

我想在spec/unit/resources/novowel_spec.rb

中编写单元测试

确保名称 属性 即使正则表达式因某种原因被更改也能正常工作。

我浏览了几本一流的 Chef 食谱,但找不到此类测试的参考资料。

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

更新 1: 难道当 属性 不适合 regex 时 Chef 不会失败?显然这不应该工作:

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) but I also use a bunch of custom helpers on top of plain ChefSpec so it might not be super helpful. Doing in-line recipe code blocks in the specs makes it waaaay easier. I've started extracting my helpers out for external use in https://github.com/poise/poise-spec,但还没有完成。目前的助手在我的 Halite gem 中,请参阅那里的自述文件以获取更多信息。

我们将 DSL 包裹在 Ruby 中,以便了解资源的名称 Ruby class:

# 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