我一直在rspec中得到这个验证错误。有人能告诉我哪里做错了吗?
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)>'
This is my 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
我在模块SocketClient
中定义了方法connect
。我不明白为什么测试总是失败
类 MyClient
没有方法命名为connect
。试试吧:MyClient.connect
行不通。
如果你想检查一个类为它的实例定义了什么方法,使用instance_methods
: MyClient.instance_methods.include?(:connect)
将为true。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
(参见Ruby中include和extend的区别是什么?)