zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Testing Workling with RSpec

October 04, 2008 by nap · Comments

Workling is my current sauce of choice for interfacing with message queues and performing asynchronous background tasks in Rails apps. We’re using it in production in a couple of places (with Starling) and it works great. In fact, we liked it so much that we wrote about it in Practical Rails Plugins.

Anyway, one thing we didn’t discuss there was how to test your workers. I’m an RSpec junkie, and I want to make sure that my Workers are behaving the way that I expect at all times. The solution is pretty simple. I modified a code snippet written a while back by David Altenburg to spec his BackgroundRB workers…

Just add the following to your spec/spec_helper.rb:

module Workling
  class Base
    class RailsBase
      def self.register; end
    end
  end
end

worker_path = File.dirname(__FILE__) + "/../app/workers"
spec_files = Dir.entries(worker_path).select {|x| /\.rb\z/ =~ x}
spec_files -= [ File.basename(__FILE__) ]
spec_files.each { |path| require(File.join(worker_path, path)) }

Now you can add specs for your workers to spec/workers/my_worker_spec.rb:

require File.dirname(__FILE__) + '/../spec_helper'

describe MyWorker do
  it "should manufacture a new widget at the happy castle widget foundry" do
    Widget.should_receive(:find).with(1).and_return(@widget = mock_model(Widget))
    @widget.should_receive(:manufacture)
    MyWorker.asynch_manufacture_widget(:widget_id => 1)
  end
end
blog comments powered by Disqus