gpt4 book ai didi

ruby - 在 ruby​​ 中测试线程代码

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:49 25 4
gpt4 key购买 nike

我正在为 DataMapper 编写一个 delayed_job 克隆。除了工作进程中的线程外,我已经得到了我认为有效和经过测试的代码。我查看了 delayed_job 以了解如何对此进行测试,但现在有针对该部分代码的测试。下面是我需要测试的代码。想法? (顺便说一句,我正在使用 rspec)

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

最佳答案

我认为,最好的方法是对 Thread.new 方法进行 stub ,并确保任何“复杂”的东西都在它自己的方法中,可以单独测试。因此你会得到这样的东西:

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

这样您就不必为了获得所需的结果而费尽心机。

关于ruby - 在 ruby​​ 中测试线程代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1604802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com