1

Say I have this spec file:

require 'chefspec'

describe 'dummy::dummy' do
  step_into 'dummy_dummy'
  platform 'ubuntu'

  context 'creates directory' do
    recipe do
      dummy_dummy 'foo'
    end

    it { is_expected.to create_directory(Chef::Config['file_cache_path']) }
  end
end

and this resource:

unified_mode true

action :create do
  work_dir = Chef::Config['file_cache_path']

  directory work_dir
end

Everything works as expected. But if I move the variable assignment outside of the action block like this...

unified_mode true

work_dir = Chef::Config['file_cache_path']

action :create do
  directory work_dir
end

the test fails, because apparently the file_cache_path has changed!?

  1) dummy::dummy creates directory is expected to create directory "/tmp/d20220910-2861475-7k8xwa"
     Failure/Error: it { is_expected.to create_directory(Chef::Config['file_cache_path']) }
     
       expected "directory[/tmp/d20220910-2861475-7k8xwa]" with action :create to be in Chef run. Other directory resources:
     
         directory[/tmp/d20220910-2861475-8elovz]

Why? Am I not supposed to define variables outside of action blocks? Is accessing Chef::Config from chefspec not supported?

Sören
  • 1,803
  • 2
  • 16
  • 23

1 Answers1

0

We need to use action_class method of custom resource to make Ruby methods available to all actions in a custom resource. So we can write a method in your custom resource (within action_class) to return the required value.

Example:

unified_mode true

action_class do
  def work_dir
    Chef::Config['file_cache_path']
  end
end

action :create do
  directory work_dir
end

Here we have a simple method work_dir that returns the value of Chef::Config['file_cache_path'] when called.

seshadri_c
  • 6,906
  • 2
  • 10
  • 24