Thursday, March 22, 2007

wrapping stubba in stub_object method

The stub method in stubba gives me a warning when you stub :id ("Object#id will be deprecated; use Object#object_id"), which we seem to do fairly often with ActiveRecord objects. So we use a simple method called stub_object (which we wrote originally because we didn't know "stub" existed):

def stub_object(params)
object = Object.new
params.each do |attr, value|
object.stubs(attr).returns(value)
end
object
end

It gives us syntax like this:

manufacturer = stub_object(:id => 5, :name => "Ford", :telephone_number => "555-888-999")
Car.any_instance.expects(:manufacturer).returns(manufacturer)

And our manufacturer object will respond to any calls to :id, :name, or :telephone_number, without the warning for :id.

1 comment:

Sudhindra Rao said...

Shane,
We using something crisper and lightweight(meaning no coding required) in our rspec specs

require 'ostruct'

manufacturer = OpenStruct.new(:id=>1, name=>"merc", type=>"car")

and yes u guessed it .. it behaves like a manufacturer..


-Sudhindra