0

考虑以下配方:

  recipe_name = 'mongodb'
  service_name = if node['szdigi'][recipe_name]['version'].to_f < 2.6
                   'mongodb'
                 else
                   'mongod'
                 end

  conffile = "/etc/#{service_name}.conf"

  # Add configuration
  template conffile do
    source 'mongodb/mongodb-conf.erb'
    owner 'root'
    group 'root'
    mode 0o644
  end

  # Remove old config file
  file '/etc/mongodb.conf' do
    action :delete
    only_if { node['szdigi'][recipe_name]['version'].to_f >= 2.6 }
  end

...以及以下chefspec测试:

require_relative 'spec_helper'

describe 'szdigi::mongo_test' do
  before(:all) do
    @conf_file = '/etc/mongodb.conf'
  end

  context 'Mongo 2.4' do
    let(:chef_run) do
      runner = ChefSpec::SoloRunner.new
      runner.node.normal['szdigi']['mongodb']['version'] = '2.4.14'
      runner.converge(described_recipe)
    end

    it 'creates mongo conf file' do
      expect(chef_run).to create_template(@conf_file)
        .with_mode(0o644)
        .with_owner('root')
        .with_group('root')
    end

    it 'does not remove /etc/mongodb.conf' do
      expect(chef_run).not_to delete_file(@conf_file)
    end

    it 'defines authentication options' do
      expect(chef_run).to render_file(@conf_file).with_content { |content|
        expect(content).to match(/^\s*auth\s*=\s*true\s*$/)
      }
    end
  end

  context 'Mongo 2.6' do
    before :all do
      @conf_file = '/etc/mongod.conf'
    end

    let(:chef_run) do
      runner = ChefSpec::SoloRunner.new
      runner.node.normal['szdigi']['mongodb']['version'] = '2.6.12'
      runner.converge(described_recipe)
    end

    it 'creates mongo conf file' do
      expect(chef_run).to create_template(@conf_file)
        .with_mode(0o644)
        .with_owner('root')
        .with_group('root')
    end

    it 'defines authentication options' do
      expect(chef_run).to render_file(@conf_file).with_content { |content|
        expect(content).to match(/^\s*auth\s*=\s*true\s*$/)
      }
    end

    it 'removes 2.4 configuration file /etc/mongodb.conf' do
      expect(chef_run).to delete_file('/etc/mongodb.conf')
    end
  end
end

该配方完全符合我的要求:它/etc/mongodb.conf在 version 属性设置为 2.4.x 时创建,/etc/mongod.conf否则,两者都使用auth = true. 在后一种情况下,它还会删除现在已过时的/etc/mongodb.conf.

但是,只要配方包含file '/etc/mongodb.conf'资源,chefspecit 'defines authentication options'在 Mongo 2.4 上下文中就会失败:

Failure/Error:
   expect(chef_run).to render_file(@conf_file).with_content { |content|
     expect(content).to match(/^\s*auth\s*=\s*true\s*$/)
   }

   expected Chef run to render "/etc/mongodb.conf" matching:

   (the result of a proc)

   but got:

知道我应该如何render_file在 2.6 上下文中重写测试才能成功吗?

谢谢

帕特里夏

4

1 回答 1

0

我会使用一个顶层if node['szdigi'][recipe_name]['version'].to_f >= 2.6,然后将配方重组为两个分支。使用聪明的 flow-y 位很好,但不要。

于 2017-07-24T19:26:26.803 回答