[rspec-users] Mocking Net::SSH connections

aslak hellesoy aslak.hellesoy at gmail.com
Mon Apr 21 03:19:51 EDT 2008


On Mon, Apr 21, 2008 at 8:03 AM, Jamie D <jam5t3r.lists at gmail.com> wrote:
> Hi,
>
>  So I'm stuck again with creating a mock for Net::SSH, I've managed to
>  mock the call to Net::SSH.start and yield the Net::SSH mock but I am
>  totally stuck with mocking the session.shell.sync call and will also
>  need to mock the shell.send_command call also. Any help much
>  appreciated.
>

Don't mock APIs you don't own. http://rubyurl.com/53Y6

Instead - create a thin API around such APIs and have your app use
that instead. Now you have an easily mockable API.
Also make sure you have end-to-end tests that use Net::SSH without any mocking.

Aslak

>  When I run the following spec I get the error:
>  Mock 'Net::SSH' received unexpected message :shell with (no args)
>
>  I've tried things like @shell = mock(Net::SSH::Service::Shell) but
>  this also gives an error complaining that Service doe snot exist.
>
>  # test code
>     @connection = Ssh::Remote.new
>     @ssh = mock(Net::SSH)
>     Net::SSH.should_receive(:start).and_yield(@ssh)
>     Net::SSH.should_receive(:shell).and_return('something')
>
>  # library code
>  require 'net/ssh'
>
>  module Ssh
>   class Remote
>
>     def remote_command(server, user, commands=[])
>       Net::SSH.start(server, user) do |session|
>         shell = session.shell.sync
>         commands.each do |command|
>           out = shell.send_command command[:command]
>         end
>       end
>     end
>   end
>  end
>  _______________________________________________
>  rspec-users mailing list
>  rspec-users at rubyforge.org
>  http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list