ruby - 使用 ChefSpec 基于模板测试文件初始化

标签 ruby chef-infra chefspec

我的 Recipe 中有以下模板文件创建:

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 测试模板资源的文件创建?

最佳答案

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

首先,您可以使用 create_template 匹配器。这将仅匹配运行上下文中的"template"资源:

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

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

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

但是,此匹配器实际上 不会呈现模板。所以你无法检查你是否正确设置了文件特异性。

对于实际呈现内存内容:

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

您可以找到有关 render_file in the README 的更多信息.

关于ruby - 使用 ChefSpec 基于模板测试文件初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18439766/

相关文章:

ruby - 将法语(重音)字符放入 Ruby 文件中

ruby - 带有循环的 Chefspec 测试资源

ruby - 使用 'execute' 编写 Chef rspec 测试

ruby - 如何让 Berkshelf 使用本地路径作为默认站点,或取消设置默认站点?

capistrano - Chef 运行 git clone 导致主机 key 验证错误

chef-infra - 如何让包装器说明书在定义中使用其父级模板?

ruby - 使用克隆的 git repo 而不是 gem?

ruby-on-rails - rescue_from NoMethodError

ruby - 有意从代码中调用 shell 命令吗?