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
5 comments so far ↓
Korepetycje // October 05, 2008 @ 05:19 PM
Very usefull, I have to also start using RSpec for my rails apps.
Todd // October 08, 2008 @ 10:27 PM
Have you used Workling to run tasks that need to be run periodically?
ed // October 09, 2008 @ 05:06 PM
RSpec is an awesome way for testing!
Zubin // November 12, 2008 @ 06:11 PM
Very useful, thanks for that.
Formatting note: FILES should have two underscores on either side (Textile italicises text between underscores).
Treetoad // January 27, 2009 @ 08:52 AM
Any idea how to stub out the AmqpClient#connect? I've tried your spec_helper method, but the AmqpClient always raises an exception that it can't connect to my RabbitMQ instance (which isn't really surprising).
Leave a Comment
Thanks for the comment!