Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub file open in chefspec

Hi am doing test with chefspec and I find the following error.

in /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

When I run ChefSpec, I get:

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)>'

When I add a stub in default_spec.rb

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

I get this error:

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)>'
like image 877
Psyreactor Avatar asked Dec 26 '22 07:12

Psyreactor


1 Answers

You need to stub the original call:

In ChefSpec 3:

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

In ChefSpec 4:

allow(File).to receive(:exist?).and_call_original
allow(File).to receive(:exist?).with('/path/to/file').and_return('...')
like image 56
sethvargo Avatar answered Jan 06 '23 23:01

sethvargo