rubyhashrspecserverspec

using variable in the the command resource in serverspec


I have the following test in a serverspec recipe - the hash is just the whole resource as it is described in Chef (I am hoping to pipe that in at some point)

# Test Folder Permissons
# hash taken from attributes
share = {
    "name" => "example",
    "sharepath" => "d:/example",
    "fullshareaccess" => "everyone",
    "ntfsfullcontrol" => "u-dom1/s37374",
    "ntfsmodifyaccess" => "",
    "ntfsreadaccess" => "everyone"
  }

# Explicitly test individual permissions (base on NTFSSecurity module)
describe command ('get-ntfsaccess d:/example -account u-dom1\s37374') do
    its(:stdout) { should include "FullControl" }
end

The issue I am having is getting a variable into the command resource - I am new to ruby and and wondering if i am missing something.

I would like the command resource call to accept a variable instead of being hardcoded.

e.g.

describe command ('get-ntfsaccess d:/example -account "#{ntfsfullcontrol}"') do
    its(:stdout) { should include "FullControl" }
end

I have managed to use variables in the :stdout test but cannot get them working in the command line.

any help much appreciated


Solution

  • You can use a variable from your hash inside the Serverspec test like this (using modern RSpec 3):

    describe command ("get-ntfsaccess #{share['sharepath']} -account #{share['ntfsfullcontrol']") do
      its(:stdout) { is_expected.to include "FullControl" }
    end
    

    The "#{}" syntax will interpolate your variable inside a string and the hash[key] syntax will grab the value from your hash.

    You can also iterate over your hash to perform more checks like this:

    share.each |key, value| do
      describe command("test with #{key} #{value}") do
        # first loop: test with name example
        its(:stdout) { is_expected.to match(/foo/) }
      end
    end