[rspec-users] A Thread / Mock question
Tobias Grimm
listaccount at e-tobi.net
Sat Jan 20 20:25:00 EST 2007
Hi!
What I'm trying at the moment is to build specifications for some
background thread code. What I want is a class Task and a class
TaskRunner. The TaskRunner should run a task in a background thread. It
should also indicate the status of the running task when calling the
running? method.
That's basically, what I came up with so far:
class TaskRunner
def initialize
@is_running = false
end
def running?
return @is_running
end
def execute(task)
@is_running = true
Thread.new do
task.run
@is_running = false
end
end
end
class SampleTask
def run
end
end
context "The TaskRunner" do
setup do
Thread.stub!(:new).and_return do |block|
block.call
end
@runner = TaskRunner.new
end
specify "should be running when a task is executed" do
task = SampleTask.new
task.should_receive(:run) do
@runner.should_be_running
end
@runner.execute(task)
end
specify "should not be running after the task has been executed" do
@runner.execute(SampleTask.new)
@runner.should_not_be_running
end
end
I don't want to have real threads in the specs, so I mocked the Thread
class to just execute the passed block within the main thread. In the
first specification I also mock the run method of the task to check
within that method, if the TaskRunner correctly indicates it's running
status. So far this works, but maybe there is a better solution. Any
suggestions?
Is there a way to use the above mocking of Thread.new and pass a
parameter to the block executed by the thread, like this?:
def execute(task)
@is_running = true
Thread.new(task) do |task_to_execute|
task_to_execute.run
@is_running = false
end
end
How can RSpec mock Thread.new in this case?
Maybe I should introduce some kind of ThreadFactory that creates
instances of TestableThread for the specifications.
bye,
Tobias
More information about the rspec-users
mailing list