我一直在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)>'这是我的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。我不明白为什么考试总是不及格。
发布于 2016-11-13 20:35:37
类MyClient没有一个名为connect的方法。尝试一下:MyClient.connect将无法工作。
如果要检查类为其实例定义了哪些方法,请使用instance_methods:MyClient.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?)。
https://stackoverflow.com/questions/40578393
复制相似问题