2009-10-22 59 views
4

我正在爲DataMapper編寫一個delayed_job克隆。我已經得到了我認爲正在工作和測試的代碼,除了工作進程中的線程。我期待delayed_job如何測試,但現在有測試代碼的那部分。以下是我需要測試的代碼。想法? (我使用rspec的BTW)在ruby中測試線程代碼

def start 
    say "*** Starting job worker #{@name}" 
    t = Thread.new do 
    loop do 
     delay = Update.work_off(self) #this method well tested 
     break if $exit 
     sleep delay 
     break if $exit 
    end 
    clear_locks 
    end 

    trap('TERM') { terminate_with t } 
    trap('INT') { terminate_with t } 

    trap('USR1') do 
    say "Wakeup Signal Caught" 
    t.run 
    end 

this thread

+0

「又見這個線索」 - 那雙雙有意? – 2011-07-01 10:41:13

+0

只有當你想要它時 – 2011-07-01 20:44:21

回答

3

你可以啓動工作作爲子測試時,等待它完全開始,然後檢查輸出/發送信號。

我懷疑你可以從Unicorn這個項目中找到這方面的一些具體測試思路。

0

看到它不可能測試線完全。最好你可以做的是使用嘲笑。

(像) object.should_recieve(:陷阱)。。隨着( 'TERM')和屈服 object.start

0

如何讓線程在測試中正確輸出?

Thread.stub(:new).and_yield 
start 
# assertions... 
8

最好的方法,我相信,是存根Thread.new方法,並確保任何「複雜」的東西是在它自己的方法,該方法可以單獨進行測試。因此,你將有這樣的事情:

class Foo 
    def start 
     Thread.new do 
      do_something 
     end 
    end 
    def do_something 
     loop do 
      foo.bar(bar.foo) 
     end 
    end 
end 

然後,你將測試這樣的:

describe Foo 
    it "starts thread running do_something" do 
     f = Foo.new 
     expect(Thread).to receive(:new).and_yield 
     expect(f).to receive(:do_something) 
     f.start 
    end 
    it "do_something loops with and calls foo.bar with bar.foo" do 
     f = Foo.new 
     expect(f).to receive(:loop).and_yield #for multiple yields: receive(:loop).and_yield.and_yield.and_yield... 
     expect(foo).to receive(:bar).with(bar.foo) 
     f.do_something 
    end 
end 

這樣你就不必HAX各地這麼多的得到期望的結果。

+1

這是解決我的問題的方式。謝謝! – Arnlen 2015-04-15 14:18:20

+0

@Arnlen很高興我能幫忙:) – Automatico 2015-04-16 13:50:14