3

我创建了一个简单的 Puppet 4 类和一个单元测试,如下所示(在执行touch metadata.json; rspec-puppet-initwhile in之后modules/test/):

# modules/test/manifests/hello_world1.pp
class test::hello_world1 {
  file { "/tmp/hello_world1":
    content => "Hello, world!\n"
  }
}

# modules/test/spec/classes/test__hello_world1_spec.rb
require 'spec_helper'
describe 'test::hello_world1' do
  it { is_expected.to compile }
  it { is_expected.to contain_file('/tmp/hello_world1')\
    .with_content(/^Hello, world!$/) }
end

我可以通过执行rspec spec/classes/test__hello_world1_spec.rbwhile in来成功运行单元测试modules/test/

我现在想继续学习一个更高级的类,它使用来自另一个模块的代码,即concat(该模块已经安装在 arleady 中modules/concat):

# modules/test/manifests/hello_world2.pp
class test::hello_world2
{
  concat{ "/tmp/hello_world2":
    ensure => present,
  }
  concat::fragment{ "/tmp/hello_world2_01":
    target  => "/tmp/hello_world2",
    content => "Hello, world!\n",
    order   => '01',
  }
}

# modules/test/spec/classes/test__hello_world2_spec.rb
require 'spec_helper'
describe 'test::hello_world2' do
  it { is_expected.to compile }
  # ...
end

当我尝试使用rspec spec/classes/test__hello_world2_spec.rbwhile in运行此单元测试时,modules/test我收到一条错误消息,其中包括:

失败/错误:编译期间它 { is_expected.to compile } 错误:评估错误:评估资源语句时出错,未知资源类型:'concat'

我怀疑根本原因是rspec找不到其他模块,因为它没有被告知“模块路径”。

我的问题是:我应该如何开始单元测试,尤其是需要访问其他模块的单元测试?

4

1 回答 1

5

下载页面为您的平台安装PDK。使用、 和或 按照指南重新创建模块。pdk new modulepdk new class

现在,我来谈谈您的代码中可能最直接的问题:您的代码依赖于 Puppet Forge 模块,puppetlabs/concat但您尚未使其可用。PDK 模块模板已经预先配置puppetlabs_spec_helper为您的模块加载夹具。

要告诉puppetlabs_spec_helper您获取它,您需要一个.fixtures.yml包含以下内容的文件:

fixtures:
  forge_modules:
    stdlib: puppetlabs/stdlib
    concat: puppetlabs/concat

请注意,您还需要puppetlabs/stdlib,因为这是puppetlabs/concat.

如果您想探索更多夹具的可能性,请参阅puppetlabs_spec_helper的文档

有了所有这些,并将您发布的代码示例和测试内容集成到 PDLK 提供的初始代码框架中,您的测试现在将在您运行时全部通过:

$ pdk test unit

请注意,我已经在一篇博文中写了所有关于底层技术的内容,展示了如何从头开始设置 Rspec-puppet 等(参考),它似乎仍然是关于这个主题的最新参考。

要阅读有关 rspec-puppet 的更多信息,请参阅官方rspec-puppet 文档站点

于 2017-08-21T14:54:25.080 回答