我有一堆重复的代码来操作 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
块放在哪里,如果有可能的话。