1

我有一堆重复的代码来操作 Puppet 目录对象(注意重复的content =行):

require 'nokogiri'

describe 'role::jenkins' do
  before(:each) do
    @jobs = catalogue.resource_keys.select{|k,v| k == 'Jenkins::Jobs'}.map{|k,v| v}
  end

  it 'Jenkins jobs should be valid XML' do
    @jobs.each do |j|
      content = catalogue.resource('file', "/tmp/#{j}.xml").send(:parameters)[:content]
      result = Nokogiri::XML(content).errors.empty?
      if ! result
        puts "    Job #{j} does NOT have valid XML"
      end
      expect(result).to be true
    end
  end 

  it "XML should contain a variables.json snippet that is valid JSON" do
    @jobs.each do |j|
      content = catalogue.resource('file', "/tmp/#{j}.xml").send(:parameters)[:content]
      if content.match(/cat << EOF > #{json_file}.*?EOF/m)
        json_snippet = content.match(/#{json_file}(.*?)EOF/m)[1]
        expect { JSON.parse(json_snippet) }.to_not raise_error
      end
    end
  end
end

可以看出,我已经将一个长查询移动到一个before(:each)块中并将其保存在一个实例变量中。这使得它在it块中可用。

我不明白的是如何为content =线条定义方法,例如:

def content(file_name)
  catalogue.resource('file', file_name).send(:parameters)[:content]
end

如果我知道该怎么做,我可以大大清理这段代码。我不知道我可以把这个def块放在哪里,如果有可能的话。

4

1 回答 1

0

我犯了一个愚蠢的错误(以为我已经尝试过,但实际上我没有尝试过)。

答案也只是放在块defbefore

require 'nokogiri'

describe 'role::jenkins' do
  before(:each) do
    @jobs = catalogue.resource_keys.select{|k,v| k == 'Jenkins::Jobs'}.map{|k,v| v}

    def content(file_name)
      catalogue.resource('file', file_name).send(:parameters)[:content]
    end
  end

  it 'Jenkins jobs should be valid XML' do
    @jobs.each do |j|
      result = Nokogiri::XML(content("/tmp/#{j}.xml").errors.empty?
      if ! result
        puts "    Job #{j} does NOT have valid XML"
      end
      expect(result).to be true
    end
  end 

  it 'XML should contain a variables.json snippet that is valid JSON' do
    @jobs.each do |j|
      content = content("/tmp/#{j}.xml")
      if content.match(/cat << EOF > #{json_file}.*?EOF/m)
        json_snippet = content.match(/#{json_file}(.*?)EOF/m)[1]
        expect { JSON.parse(json_snippet) }.to_not raise_error
      end
    end
  end
end

请让我知道,如果有人可以看到任何进一步的改进!

于 2017-05-07T08:05:12.693 回答