红宝石中的模拟系统调用 [英] Mock system call in 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{…}
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
这篇关于红宝石中的模拟系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文