2016-11-13 221 views
0

我一直在rspec中得到這個驗證錯誤。有人能告訴我做錯了什麼嗎?rspec測試失敗 - methods.include?

1) MyServer uses module 
Failure/Error: expect(MyClient.methods.include?(:connect)).to be true 

    expected true 
     got false 
# ./spec/myclient_spec.rb:13:in `block (2 levels) in <top (required)>' 

這是我client.rb

#!/bin/ruby 
require 'socket' 

# Simple reuseable socket client 

module SocketClient 

    def connect(host, port) 
    sock = TCPSocket.new(host, port) 
    begin 
     result = yield sock 
    ensure 
     sock.close 
    end 
    result 
    rescue Errno::ECONNREFUSED 
    end 
end 

# Should be able to connect to MyServer 
class MyClient 
    include SocketClient 
end 

這是我spec.rb

describe 'My server' do 

    subject { MyClient.new('localhost', port) } 
    let(:port) { 1096 } 

    it 'uses module' do 
    expect(MyClient.const_defined?(:SocketClient)).to be true 
    expect(MyClient.methods.include?(:connect)).to be true 
    end 

我有方法connect模塊SocketClient定義。我不明白爲什麼測試會失敗。

回答

0

MyClient有一個方法命名爲connect。試試看:MyClient.connect將無法​​正常工作。

如果你想檢查類定義其實例什麼方法,用instance_methodsMyClient.instance_methods.include?(:connect)將是真實的。 methods列出了對象本身響應的方法,因此MyClient.new(*args).methods.include?(:connect)將爲真。

真的,不過,用於檢測是否對你應該使用method_defined?一類存在特定實例方法,以及用於檢查對象本身是否響應特定的方法,你應該使用respond_to?

MyClient.method_defined?(:connect) 
MyClient.new(*args).respond_to?(:connect) 

如果你真的想要MyClient.connect直接工作,你需要使用Object#extend而不是Module#include(見What is the difference between include and extend in Ruby?)。