ruby 中的模拟系统调用 [英] Mock system call in ruby

查看:17
本文介绍了ruby 中的模拟系统调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Know of a way to mock %[]? I'm writing tests for code that makes a few system calls, for example:

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

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

and would like to avoid actually executing system calls while testing this method. Ideally I'd like to mock %x[..] and assert that the correct shell command is passed to it.

推荐答案

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

%x{…} is Ruby built-in syntax that will actually call Kernel method Backtick (`). So you can redefine that method. As backtick method returns the standard output of running cmd in a subshell, your redefined method should return something similar to that ,for example, a string.

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

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

这篇关于ruby 中的模拟系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆