Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec Mocks: mock / yield the block from a method call

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.

like image 620
Derick Bailey Avatar asked Oct 16 '09 19:10

Derick Bailey


1 Answers

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.

like image 104
Avdi Avatar answered Sep 21 '22 12:09

Avdi