2011-05-28 56 views
3

我有以下代碼你如何使用測試代碼叉rspec的

def start_sunspot_server 
    unless @server 
     pid = fork do 
     STDERR.reopen("/dev/null") 
     STDOUT.reopen("/dev/null") 
     server.run 
     end 

     at_exit { Process.kill("TERM", pid) } 

     wait_until_solr_starts 
    end 
    end 

我將如何有效地去使用RSpec的測試呢?

我想的東西沿

Kernel.should_receive(:fork) 
STDERR.should_receive(:reopen).with("/dev/null") 
STDOUT.should_receive(:reopen).with("/dev/null") 
server.should_receive(:run) 

回答

10

我由@server實例變量,並在你的榜樣server方法困惑,但這裏有一個例子,應該幫助你得到你在哪裏試圖去:

class Runner 
    def run 
    fork do 
     STDERR.reopen("/dev/null") 
    end 
    end 
end 

describe "runner" do 
    it "#run reopens STDERR at /dev/null" do 
    runner = Runner.new 

    runner.should_receive(:fork) do |&block| 
     STDERR.should_receive(:reopen).with("/dev/null") 
     block.call 
    end 

    runner.run 
    end 
end 

的關鍵是fork消息被髮送到Runner對象本身,即使它的實現在Kernel模塊中。

HTH, 大衛

+0

如果我嘲笑對象(使用'expect'匹配器),但如果我使用'allow'匹配器來存根對象(stub)時可以使它工作,我就無法使它工作。如果存根未被調用,則測試不會失敗,但您將在輸出中看到錯誤。建議通過指定它應該接收的參數來使存根特定。 – Dennis 2016-07-20 13:26:34

1

大衛的解決方案並沒有爲我們工作。也許是因爲我們沒有使用RSpec 2?

這是什麼工作。

def run 
    fork do 
    blah 
    end 
end 

describe '#run' do 
    it 'should create a fork which calls #blah' do 
    subject.should_receive(:fork).and_yield do |block_context| 
     block_context.should_receive(:blah) 
    end 

    subject.run_job 
    end 
end 

我不知道如何調用一個恆定的,比如STDERR當這種將適用,但是這是我們能夠做到叉測試的唯一方法。

+0

它爲我工作,我最終也在另一個地方使用它,並沒有任何問題,我相信我在兩種情況下都使用Rspec2。 – ErsatzRyan 2011-06-29 15:12:51