ruby - 在 Ruby 中使 rspec 测试通过

标签 ruby testing rspec

我有一个测试,我需要为其编写代码以使其通过。 测试是这样的:

require 'lib/String.rb'
RSpec.describe String do
  context '.to_h' do
    let(:hash) { { 'hello' => 'tree' } }

    it 'it should return the string parsed as a hash' do
      expect(hash.to_s.gsub('=>', ':').to_h).to eq(hash)
    end

    it 'should raise parse error if there was a parsing error' do
      expect { hash.to_s.to_h }.to raise_error(String::ParseError)
      expect(String::Error).to be < StandardError
      expect(String::ParseError).to be < String::Error
    end
  end
end

到目前为止我写的代码是:

class String
    class ParseError < StandardError
        def initialize
            String.const_set("Error", self)
        end
    end

    def to_h
        if self.split(":").count>1
             eval(self.split(":")[0]+"=>"+self.split(":")[1])
        else
            raise ParseError
        end
    end
end

在测试中我有“expect(String::Error).to be < StandardError”。我不明白这个说法是什么意思。什么是 String::Error 以及这种情况下的“<”运算符是什么?

最佳答案

In the test I have expect(String::Error).to be < StandardError. I don't understand what this statement means.

意思是String::Error应该继承自 StandardError .同样对于 String::ParseError .

What is the String::Error

这是一个类/常量。

and what the the "<" operator in this case?

运算符“小于”在类上使用时具有特殊行为。如果一个类是其后代,则该类被认为“小于”另一个类。


Maybe it's too much to ask but it would really help me a lot if someone could write the code for this spec.

我不打算写出所有的实现,但人们通常是这样定义自定义异常类的。

class String
  class Error < StandardError
  end

  class ParseError < Error # Error is resolved to String::Error here, which is defined above
  end
end

如果您的异常类不包含任何自定义方法,这是上述的更好/更短的形式。

class String
  Error = Class.new(StandardError)
  ParseError = Class.new(Error)
end

关于ruby - 在 Ruby 中使 rspec 测试通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51405630/

相关文章:

ruby-on-rails - 清理测试数据库,仅包含使用 RSPEC 和 Capybara 运行测试生成的数据

ruby-on-rails - 未定义的方法 `receive_message_chain'

ruby-on-rails - sublime text ruby​​ 测试窗口找不到路径

ruby - 如何在 Ruby 中的给定类上动态创建方法?

ruby-on-rails - Rails + Mongoid - 不要在 JSON 中返回 nil 值

ruby - 在mongoid中查询和排序嵌入式文档

c# - .Net 测试项目的用户特定数据和 secret 数据存储在哪里?

testing - 使用 OPA 在 SAPUI5 中进行负测试

java - 为什么我应该使用 Hamcrest-Matcher 和 assertThat() 而不是传统的 assertXXX()-Methods

ruby - 为什么 ruby​​-debug 不允许我在规范中查看局部变量?