[rspec-users] Stub that returns hash values

Carl Graff cagraff at cox.net
Wed Oct 21 13:12:48 EDT 2009

Well i just started using RSpec about a week ago and mostly I was just 
trying to learn how to use mocks as I could have easily just created the 
real object in this case.

Anyway, I had a real object, that needed to contain a hash of a yet to 
be created object, which itself contained a hash of attributes.

Here is the code that I used to get the tests to past - but it simulated 
a method called "name" in the mock that returned a string value instead 
of a hash of string values I desired.

describe ErpItemMasterRec do
context "initializing" do
before(:each) do
@itemNo = '004-907019-004'
@plmItm = ErpItemMasterRec.new(@itemNo)
['GT','CH','NB'].each do |site|
plmSiteItem = stub('plmSiteItem', :name => "#{site}-site")
@plmItm.sites[site] = plmSiteItem

it "should create new instance when receiving a valid item number as a 
string" do
@itemNo.should be_instance_of(String)
@plmItm.should be_instance_of(ErpItemMasterRec)

it "should store item data from each mfg site that contains the valid 
item number" do
@plmItm.sites['GT'].name.should == 'GT-site'
@plmItm.sites['CH'].name.should == 'CH-site'
@plmItm.sites['NB'].name.should == 'NB-site'

I wanted the last part to be more like:

it "should store item data from each mfg site that contains the valid 
item number" do
@plmItm.sites['GT'].attr['NAME'].should == 'GT-site'
@plmItm.sites['CH'].attr['NAME'].should == 'CH-site'
@plmItm.sites['NB'].attr['NAME'].should == 'NB-site'

In truth, due to my inexperience and confusion, mocks seem to slow my 
development more than just creating real objects. But since there has 
been so much effort to put these into testing frameworks, I think it 
must be important to try and learn when it is appropriate to use them.


Ashley Moran wrote:
> On 21 Oct 2009, at 08:41, Pat Maddox wrote:
>> wait why do you want to do this?? Just use a regular hash and do
>> state-based assertions on it. Or determine the role that this
>> hash-like thing is doing, and use a mock to define a proper interface.
>> Ashley's solution works but I am very skeptical that the approach is
>> a good one. Can you post some code?
> I had wondered the same thing myself... but I figured if my suspicions 
> were right, a fallout problem would be posted soon enough :)
> Ashley

More information about the rspec-users mailing list