roo*_*e09 3 unit-testing rspec puppet rspec-puppet
我创建了一个简单的 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
Run Code Online (Sandbox Code Playgroud)
我可以通过rspec spec/classes/test__hello_world1_spec.rb在modules/test/.
我现在想继续学习一个稍微高级一点的类,它使用另一个模块的代码,即concat(该模块已经安装在 中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
Run Code Online (Sandbox Code Playgroud)
当我尝试使用rspec spec/classes/test__hello_world2_spec.rbwhile in运行此单元测试时,modules/test我收到一条错误消息,其中包括:
失败/错误:它 { is_expected.to compile } 编译期间错误:评估错误:评估资源语句时出错,未知资源类型:'concat'
我怀疑根本原因是rspec找不到其他模块,因为它没有被告知“模块路径”。
我的问题是:我应该如何开始单元测试,尤其是需要访问其他模块的单元测试?
从下载页面为您的平台安装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
Run Code Online (Sandbox Code Playgroud)
请注意,您还需要puppetlabs/stdlib,因为这是 的依赖项puppetlabs/concat。
如果您想探索更多夹具的可能性,请参阅puppetlabs_spec_helper的文档。
有了所有这些,并将您发布的代码示例和测试内容集成到 PDLK 提供的初始代码框架中,您的测试现在将在您运行时全部通过:
$ pdk test unit
Run Code Online (Sandbox Code Playgroud)
请注意,我已经在博客文章中写了所有关于底层技术的内容,展示了如何从头开始设置 Rspec-puppet 等(参考),它似乎仍然是关于这个主题的最新参考。
要阅读有关 rspec-puppet 的更多信息,请参阅官方rspec-puppet 文档站点。