如何使用rspec存根/模拟对命令行的调用?
我正在尝试从命令行工具测试输出。 如何使用rspec“伪造”命令行调用? 执行以下操作不起作用:
it "should call the command line and return 'text'" do @p = Pig.new @p.should_receive(:run).with('my_command_line_tool_call').and_return('result text') end
如何创建该存根?
这是我做的一个简单例子。 我从我的假class上打电话给我。 用rspec测试
require "rubygems" require "spec" class Dummy def command_line system("ls") end end describe Dummy do it "command_line should call ls" do d = Dummy.new d.should_receive("system").with("ls") d.command_line end end
使用新消息期望语法 :
投机/ dummy_spec.rb
require "dummy" describe Dummy do it "command_line should call ls" do d = Dummy.new expect(d).to receive(:system).with("ls") d.command_line end end
LIB / dummy.rb
class Dummy def command_line system("ls") end end
或者,您可以重新定义内核系统方法:
module Kernel def system(cmd) "call #{cmd}" end end > system("test") => "call test"
信用归结为这个问题: 用ruby模拟系统调用