[rspec-users] mocking methods that receive blocks - back to mocking Thread again

Tobi listaccount at e-tobi.net
Thu Jan 25 06:36:16 EST 2007


Hi again,

my last example wasn't good either. It really makes only sense in the 
context of using Thread.

I finally came up with this code, that should now test all important 
aspects of running a task in a background thread (to keep it simple, I 
left out the exception handling).

see http://pastie.caboo.se/35559 or end of mail.

It seems, TaskRunner is now very well covered by the specs - if you find 
a way to break TaskRunner without breaking the specs, please let me know.
Unfortunately the specifications seem to be a little bit hard to read 
now. Any suggestions for improvements?

bye,

Tobias

class TaskRunner
    def initialize
        @is_running = false
    end
  
    def running?
        return @is_running
    end
  
    def execute(task)
        @is_running = true
        Thread.new(task) do |myTask|
            myTask.run
            @is_running = false
        end
    end
end

context "The TaskRunner" do
    setup do
        @runner = TaskRunner.new
        @task = mock('SampleTask')
        @task.stub!(:run)
        Thread.stub!(:new)
    end

    specify "should not run a task in the main thread" do
        @task.should_not_receive(:run)
        @runner.execute(@task)
    end

    specify "should run a task in a new thread" do
        Thread.should_receive(:new).with(@task).and_yield(@task)
        @task.should_receive(:run)
        @runner.execute(@task)
    end
   
    specify "should be running while a task is beeing executed" do
        Thread.should_receive(:new).with(@task).and_yield(@task)
        @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
        Thread.should_receive(:new).with(@task).and_return do |task, block|
            block.call(task)
            @runner.should_not_be_running
        end
        @runner.execute(@task)
    end
end



More information about the rspec-users mailing list