diff --git a/README.md b/README.md index 3f177212..48b2ba6f 100644 --- a/README.md +++ b/README.md @@ -443,6 +443,28 @@ To do this, pass a lambda as the value for the custom fact. The lambda is passed add_custom_fact :root_home, lambda { |os,facts| "/tmp/#{facts['hostname']}" } ``` +#### Merge into existing facts + +You can also supply an optional input `:merge_facts` to the `add_custom_fact` method. + +This allows you to merge facts values into a fact, if the fact is already present in the facts hash as oppose to overwriting the fact value. + +```ruby +add_custom_fact 'identity', { 'user' => "test_user" }, :merge_facts => true +``` + +Will result in a hash of the identity fact like the below: + +```ruby +{ + "gid"=>0, + "group"=>"root", + "privileged"=>true, + "uid"=>0, + "user"=>"test_user" +} +``` + ### Supplying Custom External Facts through FacterDB Rspec-puppet-facts uses a gem called facterdb that contains many fact sets of various combinations that are pre generated. Rspec-puppet-facts queries facterdb to pull out a specific fact set to use when testing. diff --git a/lib/rspec-puppet-facts.rb b/lib/rspec-puppet-facts.rb index 2d9e1e48..50691c5a 100644 --- a/lib/rspec-puppet-facts.rb +++ b/lib/rspec-puppet-facts.rb @@ -229,10 +229,13 @@ def self.with_custom_facts(os, facts) next if fact[:options][:confine] && !fact[:options][:confine].include?(os) next if fact[:options][:exclude] && fact[:options][:exclude].include?(os) - if fact[:value].respond_to?(:call) + # if merge_facts passed, merge supplied facts into facts hash + if fact[:options][:merge_facts] && fact[:value].respond_to?(:call) facts = facts.deep_merge!({name.to_sym => fact[:value].call(os, facts)}) - else + elsif fact[:options][:merge_facts] facts = facts.deep_merge!({name.to_sym => fact[:value]}) + else + facts[name.to_sym] = fact[:value].respond_to?(:call) ? fact[:value].call(os, facts) : fact[:value] end end diff --git a/spec/rspec_puppet_facts_spec.rb b/spec/rspec_puppet_facts_spec.rb index 64dab39d..734cea0b 100644 --- a/spec/rspec_puppet_facts_spec.rb +++ b/spec/rspec_puppet_facts_spec.rb @@ -904,6 +904,22 @@ expect(subject['redhat-7-x86_64'][:root_home]).to eq '/root' end + it 'deep merges fact and values' do + add_custom_fact 'identity', { 'user' => "test_user" }, :merge_facts => true + expect(subject['redhat-7-x86_64'][:identity]).to eq({ + "gid"=>0, + "group"=>"root", + "privileged"=>true, + "uid"=>0, + "user"=>"test_user" + }) + end + + it 'overwrites fact and values' do + add_custom_fact 'identity', { 'user' => 'root' } + expect(subject['redhat-7-x86_64'][:identity]).to eq({ 'user' => 'root' }) + end + it 'confines a fact to a particular operating system' do add_custom_fact 'root_home', '/root', :confine => 'redhat-7-x86_64' expect(subject['redhat-7-x86_64'][:root_home]).to eq '/root'