2009-11-10 14 views
5

Sto provando a testare l'output da uno strumento da riga di comando. Come faccio a "fingere" una chiamata da riga di comando con rspec? Non funziona quanto segue:Come faccio a stub/mock una chiamata alla riga di comando con 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 

Come si crea quel tronchetto?

+0

Possiamo vedere le rilevanti pezzi della classe 'suino? – hgmnz

risposta

6

Ecco un esempio rapido che ho creato. Chiamo ls dalla mia classe dummy. Testato con 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 
+0

Poifect: -) ... Grazie! – btelles

+0

Penso di aver avuto altri bug proibitivi che non erano nemmeno arrivati ​​alla chiamata run/system. – btelles

+8

In che modo si sta eseguendo lo stub o la chiamata di sistema? – Automatico

-5

alternativa, si può solo ridefinire il metodo di sistema di kernel:

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

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

E il merito va a questa domanda: Mock system call in ruby

+1

Perché questa risposta ottiene così tanti downvotes? La risposta a cui si riferisce @jpatokal ha 17 voti positivi! – hagello

+0

Presumibilmente perché non è lo stub/mocking, ma in realtà * sostituisce * il metodo. Poi di nuovo, vorresti mai effettuare chiamate di sistema effettive nei test? – jpatokal

11

Utilizzando la 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 
Problemi correlati