2016-11-13 311 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?)。