如何使用rspec存根/模拟对命令行的调用?

时间:2009-11-10 15:09:45

标签: ruby command-line 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

如何创建该存根?

3 个答案:

答案 0 :(得分:12)

使用new message expectation syntax

规格/ 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

答案 1 :(得分:6)

这是我做的一个简单例子。我从我的假类中调用 ls 。用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

答案 2 :(得分:-4)

替代方案,您可以重新定义内核系统方法:

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

> system("test")
=> "call test" 

并且归功于这个问题:Mock system call in ruby