无法在厨师食谱中 运行 rspec 单元测试 "touch_file"

Unable to run rspec unit test "touch_file" in chef cookbook

食谱:https://github.com/tkidd77/devops-project/tree/master/chef-repo/cookbooks/hello_world

我的单元测试:

it 'touches the correct file' do
  expect { chef_run }.to touch_file ('C:\inetpub\wwwroot\iisstart.htm')
end

当运行"chef exec rspec"在gitbash时输出:

tkidd@tkiddhome MINGW64 /c/git/project/chef-repo/cookbooks/hello_world (master) $ chef exec rspec .F

Failures:

  1) hello_world::default touches the correct file
     Failure/Error: expect { chef_run }.to touch_file ('C:\inetpub\wwwroot\iisstart.htm')
       You must pass an argument rather than a block to use the provided matcher ( file "C:\inetpub\wwwroot\iisstart.htm"), or the matcher must implement `supports_block_expectations?`.
     # ./spec/unit/recipes/default_spec.rb:38:in `block (2 levels) in <top (required)>'

Finished in 0.07199 seconds (files took 8.68 seconds to load) 2 examples, 1 failure

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:37 # hello_world::default touches the correct file

这是关于使用 touch_file 测试的 chefspec 文档:https://www.rubydoc.info/github/acrmp/chefspec/ChefSpec/API/FileMatchers 指定在 "chef-run" 周围使用圆括号而不是方括号,但是当我这样做时,我收到一个 "undefined method" 错误:

tkidd@tkiddhome MINGW64 /c/git/project/chef-repo/cookbooks/hello_world (master) $ chef exec rspec .F

Failures:

  1) hello_world::default touches the correct file
     Failure/Error: expect (chef_run).to touch_file ('C:\inetpub\wwwroot\iisstart.htm')

     NoMethodError:
       undefined method `to' for #<ChefSpec::SoloRunner:0x0000000007a241d8>
     # ./spec/unit/recipes/default_spec.rb:38:in `block (2 levels) in <top (required)>'

Finished in 0.04001 seconds (files took 4.92 seconds to load) 2 examples, 1 failure

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:37 # hello_world::default touches the correct file

据此,rspec 3.0 需要一个方法而不是文件路径块,但我不明白那会是什么样子。 How to check whether a variable is an instance of a module's subclass using rspec?

应该是expect(chef_run).to touch_file('C:\inetpub\wwwroot\iisstart.htm')。您只能将 expect { ... }raise_error 和类似的东西一起使用,大多数匹配使用 expect(...) 作为正常调用。在 touch_file 之后还有一个额外的 space。 method (args) 在 Ruby 中是不允许的(或者至少它是允许的,并且不会按照您的想法去做)。

解决方案:

describe 'hello_world::default' do

  let :chef_run do
    ChefSpec::SoloRunner.new(platform: 'windows', version: '2016').converge(described_recipe)
  end

     it 'touches the correct file' do
       expect(chef_run).to touch_file('C:\inetpub\wwwroot\iisstart.htm')
     end
end