【问题标题】:Test file initialization based off template using ChefSpec使用 ChefSpec 基于模板测试文件初始化
【发布时间】:2014-02-02 03:00:59
【问题描述】:

我的食谱中创建了以下模板文件:

template "my_file" do
  path "my_path"
  source "my_file.erb"
  owner "root"
  group "root"
  mode "0644"
  variables(@template_variables)
  notifies :restart, resources(service: "my_service")
end

以及我的 ChefSpec 测试中的以下断言:

  chef_run.should create_file "my_file"
  chef_run.file("my_file").should be_owned_by('root', 'root')

这会导致以下失败:

  No file resource named 'my_file' with action :create found.

这是因为我使用的不是file 资源,而是template 资源。问题:如何使用 ChefSpec 测试模板资源的文件创建?

【问题讨论】:

  • 您找到解决问题的方法了吗?自发布此问题以来,ChefSpec 匹配器的语法已更改。给定的答案能解决您的问题吗?
  • o 很抱歉,我完全忘记了这个问题。我要去重新检查一下,看看

标签: ruby chef-infra chefspec


【解决方案1】:

有两种方法可以解决您的问题。

首先,您可以使用create_template 匹配器。这将只匹配运行上下文中的“模板”资源:

expect(chef_run).to create_template('my_file')

这个匹配器也是可链接的,所以你可以断言属性:

expect(chef_run).to create_template('my_file')
  .with_path('my_path')
  .with_owner('root')

然而,这个匹配器不会实际上渲染模板。因此,您无法检查是否正确设置了文件特异性。

对于任何类型的“文件”(filecookbook_filetemplate)还有一个顶级匹配器,它实际上在内存中呈现内容:

expect(chef_run).to render_file('my_file').with_content(/^match me$/)

你可以找到更多关于render_file in the README的信息。

【讨论】:

  • 我的 chefspec 的质量刚刚提高了 3 倍。是否可以使用多个 with_content 集? should render_file('somefile').with_content(/content1/).with_content(/content2/) 只匹配第二个正则表达式,从不解析第一个。
  • 不,with_content 不是加法匹配器。
  • 因此,测试多个内容匹配的方法是将.to render_file('myfile') 分配给一个变量,然后针对该变量运行 with_content。
【解决方案2】:

根据文档 (https://github.com/acrmp/chefspec),您应该可以使用:

expect(chef_run).to create_file 'my_file'

我认为最近发生了一些变化(可能是 ruby​​gems 上的 chefspec 版本),因为我今天早些时候通过的测试(使用您使用的相同语法)现在突然失败了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多