I'm writing a delayed_job
clone for DataMapper. I've got what I think is working and tested code except for the thread in the worker process. I looked to delayed_job
for how to test this but there are now tests for that portion of the code. Below is the code I need to test. ideas? (I'm using 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
see also this thread
You could start the worker as a subprocess when testing, waiting for it to fully start, and then check the output / send signals to it.
I suspect you can pick up quite a few concrete testing ideas in this area from the Unicorn project.
The best approach, I believe, is to stub the
Thread.new
method, and make sure that any "complicated" stuff is in it's own method which can be tested individually. Thus you would have something like this:Then you would test like this:
This way you don't have to hax around so much to get the desired result.
Its impossible to test threads completely. Best you can do is to use mocks.
(something like) object.should_recieve(:trap).with('TERM').and yield object.start
How about just having the thread yield right in your test.