unit-testing - 启动 RSpec-puppet 单元测试的正确方法

标签 unit-testing rspec puppet rspec-puppet

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

# 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

我可以通过在 modules/test/ 中执行 rspec spec/classes/test__hello_world1_spec.rb 成功运行单元测试。

我现在想继续学习一个稍微高级的类,它使用另一个模块中的代码,即 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

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

Failure/Error: it { is_expected.to compile } error during compilation: Evaluation Error: Error while evaluating a Resource Statement, Unknown resource type: 'concat'

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

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

最佳答案

安装PDK适用于您的平台 download page 。使用 pdk new modulepdk new class 重新创建模块,或按照 Guide 操作.

现在,我来看看您的代码中可能存在的直接问题:您的代码依赖于 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's docs .

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

$ pdk test unit

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

要了解有关 rspec-puppet 的更多一般信息,请参阅官方 rspec-puppet docs site .

关于unit-testing - 启动 RSpec-puppet 单元测试的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45791768/

相关文章:

angularjs - Angular 自动模拟 Controller /服务依赖项

c# - 无法在 protected 方法的单元测试的适当方法之间做出决定

ruby-on-rails - 使用 Ruby on Rails 和 RSpec 为 helper 编写规范

ruby - puppet 4.10.4 : Master not reading manifest

node.js - jest-cli代码覆盖率仅显示零百分比

ruby - 使用不同的参数重复 RSpec 示例组

ruby-on-rails - .rspec 配置文件的确切位置在哪里?

linux - puppet 覆盖模块上的文件资源

puppet - RHEL 服务无法使用 Puppet 启动

java - EasyMock - 覆盖对象创建