gpt4 book ai didi

ruby - 关于 Ruby/ChefSpec 编码风格的反馈

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:12 25 4
gpt4 key购买 nike

我是 Ruby 的新手,但过去两周我一直在对 Chef 测试进行大量研究。该测试使用 ChefSpec 和 Fauxhai,但它看起来不是很“像 ruby ”,我希望社区能给我一些编码风格的建议。有没有更好的方法来编写这样的嵌套循环?

Recipe/foo/recipes/default.rb

package "foo" do
action :install
end

Recipe/foo/spec/default_spec.rb

require 'chefspec'

describe 'foo::default' do
platforms = {
"debian" => ['6.0.5'],
"ubuntu" => ['12.04', '10.04'],
"centos" => ['5.8', '6.0', '6.3'],
"redhat" => ['5.8', '6.3'],
"mac_os_x" => ['10.6.8', '10.7.4', '10.8.2'],
"windows" => ['2008R2']
}

platforms.each do |platform,versions|
versions.each do |version|
context "on #{platform} #{version}" do
before do
Fauxhai.mock(platform: platform, version: version)
end

it 'should install foo' do
@runner = ChefSpec::ChefRunner.new.converge('foo::default')
@runner.should install_package 'foo'
end
end
end
end
end

欢迎任何和所有反馈。谢谢!

最佳答案

首先,一种常见的做法是将 ChefRunner 实例化提取到 let 助手。您还可以在那里包含所有 Fauxhai 配置:

let(:chef_run) do
ChefSpec::ChefRunner.new(platform: platform, version: version) do |node|
node.set['foo']['bar'] = 'baz'
# ....
end.converge('foo::default')
end

it "installs foo" do
expect(chef_run).to install_package 'foo'
end

expect 语法似乎是 recommended超过应该。但在这个例子中,我会使用单线:

subject do
ChefSpec::ChefRunner.new(platform: platform, version: version).converge('foo::default')
end
it { should install_package 'foo' }

要稍微清理一下循环,您可以使用 RSpec's shared examples .更扩展的示例:

require 'chefspec'

shared_examples 'foo' do |platform, version|
context "on #{platform} #{version}" do
let(:users) { %w[user1 user2] }
let(:chef_run) do
ChefSpec::ChefRunner.new(platform: platform, version: version) do |node|
node.set['foo']['users'] = users
end.converge('foo::default')
end
subject { chef_run }

it { should install_package 'foo' }

it "creates specified users" do
users.each { |u| expect(chef_run).to create_user u }
end
end
end

describe 'foo::default' do
platforms = {
'debian' => ['6.0.5'],
'ubuntu' => ['12.04', '10.04'],
'centos' => ['5.8', '6.0', '6.3'],
'redhat' => ['5.8', '6.3'],
'mac_os_x' => ['10.6.8', '10.7.4', '10.8.2'],
'windows' => ['2008R2']
}

platforms.each do |platform, versions|
versions.each do |version|
include_examples 'foo', platform, version
end
end
end

关于ruby - 关于 Ruby/ChefSpec 编码风格的反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15225283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com