在chefspec中打开存根文件

时间:2014-06-17 18:28:40

标签: rspec chef chefspec

您正在使用chefspec进行测试,我发现以下错误。

/cookbook/wordpress/recipes/default.rb

中的

wp_secrets = Chef::Config[:file_cache_path] + '/wp-secrets.php'

if File.exist?(wp_secrets)
  salt_data = File.read(wp_secrets)
else
  require 'open-uri'
  salt_data = open('https://api.wordpress.org/secret-key/1.1/salt/').read
  open(wp_secrets, 'wb') do |file|
    file << salt_data
  end
end

当我运行ChefSpec时,我得到:

1) wordpress::default on Centos 6.5 includes depends recipes
   Failure/Error: end.converge('wordpress::default')
   Errno::ENOENT:
     No such file or directory @ rb_sysopen - /var/chef/cache/wp-secrets.php

   # /tmp/d20140617-408-1rx47um/cookbooks/wordpress/recipes/default.rb:77:in `from_file'
   # ./spec/centos/default_spec.rb:10:in `block (2 levels) in <top (required)>'
   # ./spec/centos/default_spec.rb:20:in `block (2 levels) in <top (required)>'

当我在default_spec.rb

中添加存根时
before do
  File.stub(:exist?)
    .with("#{Chef::Config[:file_cache_path]}/wp-secrets.php")
    .and_return(true)
end

我收到此错误:

1) wordpress::default on Centos 6.5 includes depends recipes
   Failure/Error: end.converge('wordpress::default')
     <File (class)> received :exist? with unexpected arguments
       expected: ("/var/chef/cache/wp-secrets.php")
            got: ("/tmp/d20140617-479-1gqb2lc/cookbooks/chefignore")
      Please stub a default value first if message might be received with other args as well. 
   # ./spec/centos/default_spec.rb:10:in `block (2 levels) in <top (required)>'
   # ./spec/centos/default_spec.rb:20:in `block (2 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:10)

您需要存根原始呼叫:

在ChefSpec 3中:

File.stub(:exist?).and_call_original
File.stub(:exist?).with('/path/to/file').and_return('...')

在ChefSpec 4中:

allow(File).to receive(:exist?).and_call_original
allow(File).to receive(:exist?).with('/path/to/file').and_return('...')