2011-05-28 161 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