Joh*_*ler 4 ruby multithreading unit-testing rspec
我正在delayed_job为DataMapper 编写一个克隆.除了工作进程中的线程之外,我已经得到了我认为正在工作和测试的代码.我查找delayed_job了如何测试这个,但现在有对该部分代码的测试.下面是我需要测试的代码.想法?(我正在使用rspec BTW)
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
Run Code Online (Sandbox Code Playgroud)
另见这个帖子
我认为,最好的方法是保留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
Run Code Online (Sandbox Code Playgroud)
然后你会像这样测试:
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
Run Code Online (Sandbox Code Playgroud)
这样你就不必为了获得理想的结果而烦恼.
| 归档时间: |
|
| 查看次数: |
2463 次 |
| 最近记录: |