【问题标题】:Correct way to start RSpec-puppet unit tests启动 RSpec-puppet 单元测试的正确方法
【发布时间】:2017-08-21 07:46:27
【问题描述】:

我创建了一个简单的 Puppet 4 类和一个单元测试,如下所示(在 modules/test/ 中执行 touch metadata.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 } 编译期间出错: 评估错误:评估资源语句时出错,未知 资源类型:'concat'

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

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

【问题讨论】:

    标签: unit-testing rspec puppet rspec-puppet


    【解决方案1】:

    download page 为您的平台安装PDK。使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 2022-01-14
      • 2015-07-24
      • 1970-01-01
      • 2023-03-10
      • 2012-04-20
      • 2019-02-03
      相关资源
      最近更新 更多