gpt4 book ai didi

ruby - ruby 中的模拟系统调用

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

知道模拟 %[] 的方法吗?我正在为进行一些系统调用的代码编写测试,例如:

def log(file)
%x[git log #{file}]
end

并希望在测试此方法时避免实际执行系统调用。理想情况下,我想模拟 %x[..] 并断言已将正确的 shell 命令传递给它。

最佳答案

%x{…} 是 Ruby 内置的语法,它实际上会调用内核方法 Backtick (`) .所以你可以重新定义那个方法。由于反引号方法返回在子 shell 中运行 cmd 的标准输出,您重新定义的方法应该返回类似的东西,例如,一个字符串。

module Kernel
def `(cmd)
"call #{cmd}"
end
end

puts %x(ls)
puts `ls`
# output
# call ls
# call ls

关于ruby - ruby 中的模拟系统调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1628586/

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