2016-08-16 14 views
0

ssh接続をテストするためにrspecを書き込もうとしています。私の仕様ファイルでは、たとえ私が間違ったサーバパスワードを入力したとしても、まだ0 examples, 0 failuresと言います。誰かが私に感謝することができますなぜ私はそれを見ていますが、私は少なくとも1つの失敗メッセージを見ることが期待されています。ssh接続用のRspec

以下は、私のssh_host.rbssh_host_spec.rb filesのコードです。

require "java" 
require "highline/import" 
require 'open-uri' 
require 'socket' 
require 'rubygems' 
require 'net/ssh' 
require 'stringio' 
require 'net/scp' 
require 'colorize' 

module SshMod 

class SshHost 

    attr_accessor :hostname, :username, :password 

    def initialize(host, user, password) 
      @hostname = host 
      @username = user 
      @password = password 

      @ssh = Net::SSH.start(@hostname, @username, :password => @password) 
      puts "\t Connection established for #{@hostname}...".blue 
    end 
end 
end 

RSpecのクラス:

#!/usr/bin/env rspec 

require 'spec_helper' 
require 'ssh_host.rb' 

describe SshMod::SshHost do 
    before :each do 
     @ssh = SshMod::SshHost.new "servername", "user", "wrong_password" 

    end 
end 

describe "#new" do 
    it "takes three parameters and returns sshhostobject" do 
     @ssh.should_be_an_instance_of SshHost 

    end 
end 

ssh_mock = double() 


expect(SSH).to receive(:start).and_return(ssh_mock) 

答えて

2

あなたのspecファイルで間違ったことがいくつかあります。 newのテストは、SshMod::SshHostのコンテキスト内にある必要があります。それ以外の場合は、sshインスタンス変数にアクセスできません。また、exceptがカーネルで定義されていないため、コードはRspecオブジェクトのコンテキスト内にあるため、いくつかのエラーが発生します。あなたはおそらくあなたのbeforeに入れたいと思うでしょう。

あなたのルビークラスの必要性に関して、私はあなたが必要としないすべてのものを取り除くでしょう(例えば、なぜnet-sshを使うときにソケットを明示的に組み込むのか?)。

しかし、プロジェクト構造のためにテストが実行されていない(ただし、リストされていないので推測されます)問題にぶつかっていると思います。 Rspecはデフォルトでspec/**/*_spec.rbの下にリストされたspecファイルを探します。このファイルは--patternフラグで上書きできます。詳細はrspec --helpを参照してください。

ここでは、一連のコードをクリーンアップした実例を示します。私はあなたのコードのソースをlibに入れて、あなたが宝石のようなものを作っていると仮定します。


Gemfile:

source "https://rubygems.org" 

gem "colorize" 
gem "rspec" 
gem "net-ssh" 

のlib/ssh_host.rb

require 'net/ssh' 
require 'colorize' 

module SshMod 
    class SshHost 
    attr_accessor :hostname, :username, :password 

    def initialize(host, user, password) 
     @hostname = host 
     @username = user 
     @password = password 

     @ssh = Net::SSH.start(@hostname, @username, password: @password) 
     puts "\t Connection established for #{@hostname}...".blue 
    end 
    end 
end 

スペック/ spec_helper.rb

$:.unshift File.join(File.dirname(__FILE__), '..', 'lib') 
require 'rspec' 

RSpec.configure do |config| 
    config.mock_with :rspec do |mocks| 
    mocks.verify_partial_doubles = true 
    end 
end 

スペック/ ssh_host_spec.rb

require 'spec_helper' 

require 'ssh_host' 

describe SshMod::SshHost do 
    let (:ssh) { SshMod::SshHost.new "servername", "user", "wrong_password" } 
    before :each do 
    allow(Net::SSH).to receive(:start).and_return(double("connection")) 
    end 

    describe "#new" do 
    it "takes three parameters and returns sshhostobject" do 
     expect(ssh).to be_a SshMod::SshHost 
    end 
    end 
end