[rspec-users] mocking methods that receive blocks

Tobias Grimm listaccount at e-tobi.net
Wed Jan 24 19:03:02 EST 2007


Hi!

Maybe my last (but real life) example was too boring - what about this one?

see end of mail or http://pastie.caboo.se/35443

So basically what I want to do, is mock a method that receives
parameters and a block, but I still need to execute the passed block in
order to test that it does what it is expected to do.

With a different design, I could avoid this problem. Instead of passing
blocks around I could e.g. use some kind of Strategy class.
I was just wondering if this can be done somehow with RSpec's mocking
capabilities. If not, maybe RSpec can be extended to make it possible.

bye,

Tobias

Sorry, I hold no degree in Trek physics !!! :-)

class Antimatter
    def stabilize
    end
end

class TransWarpEngine
    def TransWarpEngine.initiate(antimatter)
       create_quantum_singularity
       yield antimatter
    end
end

class BorgCube
    def travel_with_light_speed(antimatter)
        TransWarpEngine.initiate(antimatter) do |antimatter|
            antimatter.stabilize
        end
    end
end

context "The Borg Cube, when travelling with light speed" do
    setup do
        @borg_cube = BorgCube.new
    end

    specify "should initiate the TransWarpEngine with the given
antimatter" do
        antimatter = mock(Antimatter)
        TransWarpEngine.should_receive(:initiate).with(antimatter)
        @borg_cube.travel_with_light_speed(antimatter)
    end

    specify "should tell the TransWarpEngine, that the antimatter should
be stabilized" do
        antimatter = mock(Antimatter)
        antimatter.should_receive(:stabilize)

        #
        # Put in here the part, that I don't know how to do :-)
        # I must mock or stub TransWarpEngine.initiate(), because I
can't risk
        # to create a quantum singularity when running RSpec.
        # But i also must test, that my little BorgCube receives the correct
        # instructions to stabilize the antimatter, otherwise my
customer won't
        # be very happy, when she tries out the BorgCube the first time
and it
        # simply detonates because of unstabilized antimatter.
        #

        @borg_cube.travel_with_light_speed(antimatter)
    end
end



More information about the rspec-users mailing list