Class: ChefVault::TestFixtures

Inherits:
Object
  • Object
show all
Defined in:
lib/chef-vault/test_fixtures.rb

Overview

dynamic RSpec contexts for cookbooks that use chef-vault

Constant Summary collapse

VERSION =
'0.3.0'

Class Method Summary collapse

Class Method Details

.rspec_shared_contextObject

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/chef-vault/test_fixtures.rb', line 20

def rspec_shared_context
  @context ||= begin
    Module.new do
      extend RSpec::Core::SharedContext

      before { find_vaults }

      private

      def find_vaults
        dbdir = Pathname.new('test') + 'integration' + 'data_bags'
        dbdir.each_child do |vault|
          next unless vault.directory?
          stub_vault(vault)
        end
      end

      def stub_vault(vault)
        vault.each_child do |e|
          next unless e.file?
          m = e.basename.to_s.downcase.match(/(.+)\.json/i)
          stub_vault_item(vault.basename.to_s, m[1], e.read) if m
        end
      end

      def stub_vault_item(vault, item, json)
        content = JSON.parse(json)
        vi = make_fakevault(vault, item)
        # stub lookup of each of the vault item keys
        content.each do |k, v|
          next if 'id' == k
          allow(vi).to receive(:[]).with(k).and_return(v)
        end
        # stub chef-vault to return the fake vault item, via
        # both symbol and string forms of the data bag name
        [vault, vault.to_sym].each do |dbname|
          allow(ChefVault::Item).to(
            receive(:load)
            .with(dbname, item)
            .and_return(vi)
          )
        end
      end

      def make_fakevault(vault, item)
        fakevault = double "vault item #{vault}/#{item}"
        allow(fakevault).to receive(:[]=).with(String, Object)
        allow(fakevault).to receive(:clients).with(String)
        allow(fakevault).to receive(:save)
        fakevault
      end
    end
  end
end