我正在为Chef编写自定义资源。该资源用于设置sysctl值。我基本上是在使用Chef sysctl代码,并对其施加一些限制。我们不信任公司的所有用户:P
我正在尝试将大多数代码放在库帮助器模块中,以便可以更轻松地测试代码。我不确定这是否是最佳做法。让我知道这是否是不好的做法。
无论如何,我遇到的问题是试图测试我的库代码。每当我尝试模拟shell_out命令时,我总是会收到以下错误。
1) Sysctl::Helpers.set_sysctl_param
Failure/Error: subject.set_sysctl_param("key1", "value1")
NoMethodError:
undefined method `shell_out!' for Sysctl::Helpers:Module
图书馆代码
module Sysctl
module Helpers
include Chef::Mixin::ShellOut
def self.set_sysctl_param(key, value)
shell_out!("sysctl -w \"#{key}=#{value}\"")
end
end
end
测试
require 'spec_helper'
describe Sysctl::Helpers do
describe '.set_sysctl_param' do
let(:shellout) { double(run_command: nil, error!: nil, stdout: '', stderr: double(empty?: true)) }
before do
allow(Chef::Mixin::ShellOut).to receive(:new).and_return(shellout)
end
it do
subject.set_sysctl_param("key1", "value1")
expect(:shellout).to receive(:run_command).with("sysctl -w \"key1=value1\"")
end
end
end
我非常感谢您的帮助或建议,可以给我。
谢谢!
当您包括模块时,您将模块方法添加为实例方法。但是您尝试通过类方法访问shell_out
。实际上,您需要使用Chef :: Mixin :: ShellOut extend模块。这样,ShellOut方法将作为类方法添加。
module Sysctl
module Helpers
extend Chef::Mixin::ShellOut # replace include with extend
def self.set_sysctl_param(key, value)
shell_out!("sysctl -w \"#{key}=#{value}\"")
end
end
end
此What is the difference between include and extend in Ruby?的更多信息>