代码之家  ›  专栏  ›  技术社区  ›  dstnbrkr

ruby中的模拟系统调用

  •  20
  • dstnbrkr  · 技术社区  · 16 年前

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

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

    5 回复  |  直到 16 年前
        1
  •  17
  •   pierrotlefou    16 年前

    %x{…} Backtick (`) 。因此,您可以重新定义该方法。由于回溯方法返回在子shell中运行cmd的标准输出,因此重新定义的方法应返回类似的内容,例如字符串。

    module Kernel
        def `(cmd)
            "call #{cmd}"
        end
    end
    
    puts %x(ls)
    puts `ls`
    # output
    # call ls
    # call ls
    
        2
  •  13
  •   Jippe    16 年前

    使用 Mocha

    class Test
      def method_under_test
        system "echo 'Hello World!"
        `ls -l`
      end
    end
    

    你的测试看起来像:

    def test_method_under_test
      Test.any_instance.expects(:system).with("echo 'Hello World!'").returns('Hello World!').once
      Test.any_instance.expects(:`).with("ls -l").once
    end
    

    这是有效的,因为每个对象都从Kernel对象继承了system和`等方法。

        3
  •  3
  •   Mike Woodhouse    16 年前

    Kernel.expects

    require 'test/unit'
    require 'mocha'
    
    class SystemCaller
      def self.call(cmd)
        system cmd
      end
    end
    
    class TestMockingSystem < Test::Unit::TestCase
      def test_mocked_out_system_call
        SystemCaller.expects(:call).with('dir')
        SystemCaller.call "dir"
      end
    end
    

    Started
    .
    Finished in 0.0 seconds.
    
    1 tests, 1 assertions, 0 failures, 0 errors
    
        4
  •  0
  •   JAL    16 年前

    def log(file)
      puts "git log #{file}"
    end
    
        5
  •  -1
  •   CodeJoust    16 年前