views:

564

answers:

1

I've got this code:

Net::SSH.start(@server, @username, :password => @password) do |ssh|
      output = ssh.exec!(@command)
      @logger.info 'SSH output: '
      @logger.info output
     end

I can mock the SSH.Start using RSpec's mock framework like this, to tell me that I've started the SSH session:

Net::SSH.should_receive(:start).with("server", "user", :password => "secret") do
      @started = true
     end

this tells me whether or not i've @started the ssh session. now I need to mock the ssh.exec! method, which is easy enough:

Net::SSH.should_receive(:exec!).with("command")...

but how do I yield / call the block that contains the ssh.exec! method call, since I have mocked the SSH.start method? there's probably some simple method I can call to execute this block, but I don't know what it is and can't find any really good explanations / documentation on rspec's mocking framework.

+2  A: 
Net::SSH.should_receive(:start).with("server", "user", :password => "secret").and_yield("whatever value the block should yield")

Not sure why you need to set @started, since the should_receive verifies that the method has been called.

Avdi
didn't know that about should_receive... is there any good documentation on this stuff? my google-fu is failing me...also - what if I don't care about the return value of the yielded block? I just want it to be executed, so that i can call should_receive on the ssh.exec! method.
Derick Bailey
That's what `should_receive` means: if it isn't received, the test will fail.As far as documentation, the RSpec Book is excellent. I recommend it both for learning to use RSpec, and for learning about BDD in general.
Avdi
Oh, and you may be able to call `#and_yield()` without an argument.
Avdi