首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rspec测试失败- methods.include?

rspec测试失败- methods.include?
EN

Stack Overflow用户
提问于 2016-11-13 20:21:17
回答 1查看 120关注 0票数 0

我一直在rspec中得到这个验证错误。有人能告诉我做错了什么吗?

代码语言:javascript
复制
  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

代码语言:javascript
复制
#!/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

代码语言:javascript
复制
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。我不明白为什么考试总是不及格。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-13 20:35:37

MyClient没有一个名为connect的方法。尝试一下:MyClient.connect将无法工作。

如果要检查类为其实例定义了哪些方法,请使用instance_methodsMyClient.instance_methods.include?(:connect)methods列出了对象本身响应的方法,因此MyClient.new(*args).methods.include?(:connect)将为真。

实际上,为了检查类上是否存在特定的实例方法,您应该使用method_defined?,为了检查对象本身是否响应特定的方法,您应该使用respond_to?

代码语言:javascript
复制
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?)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40578393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档