[rspec-users] Stub that returns hash values

Carl Graff cagraff at cox.net
Tue Oct 20 23:13:09 EDT 2009


Ashley Moran wrote:
>
> On 20 Oct 2009, at 17:36, Carl Graff wrote:
>
>> Is it possible to create a stub that returns hash values.
>>
>> For example I would like to convert this:
>> @siteItem = stub('plmSiteItem', :one => "uno")
>>
>> To something like this:
>> @siteItem = stub('plmSiteItem', {'one' => 'uno', 'two' => 'dos'} )
>>
>> So that I can do this:
>> @siteItem['one'] should == 'uno'
>> @siteItem['two'] should == 'dos'
>
> Hi Carl
>
> In Ruby, code like my_object["foo"] is implemented with the method [] eg:
>
> class Thing
> def [](key)
> # ...
> end
> end
>
> So in RSpec you have to stub :[] like this:
>
> describe "stub hash" do
> it "quacks like a hash" do
> stub_hash = stub("hash")
> stub_hash.stub(:[]).with("one").and_return("uno")
> stub_hash.stub(:[]).with("two").and_return("dos")
> stub_hash["one"].should == "uno"
> stub_hash["two"].should == "dos"
> end
> end
>
>
>> Actually I first tried to use method double instead of stub - even 
>> though I still don't know when each is preferred - but double raised 
>> a missing method error for some reason.
>
>
> Can you post your code?
>
>
> HTH
>
> Ashley
>
>

Thanks Ashley that works perfect :-)


More information about the rspec-users mailing list