How do I stub/mock a call to the command line with

2019-03-29 23:37发布

I'm trying to test output from a command line tool. How do I 'fake' a command line call with rspec? Doing the following doesn't work:

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

How do I create that stub?

3条回答
乱世女痞
2楼-- · 2019-03-29 23:59

Using the new message expectation syntax:

spec/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
查看更多
该账号已被封号
3楼-- · 2019-03-30 00:18

Alternative, you could just redefine the Kernel system method:

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

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

And the credit goes to this question: Mock system call in ruby

查看更多
Lonely孤独者°
4楼-- · 2019-03-30 00:19

Here is a quick example I made. I call ls from my dummy class. Tested with 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
查看更多
登录 后发表回答