ruby - 在 Ruby 中通过 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
在测试中,我有“期望(String::Error).to < StandardError”。我不明白这句话是什么意思。在这种情况下,String::Error 和“<”运算符是什么?
解决方案
在测试中我有
expect(String::Error).to be < StandardError
. 我不明白这句话是什么意思。
这意味着String::Error
应该继承自StandardError
. 同样对于String::ParseError
。
是什么
String::Error
这是一个类/常量。
在这种情况下,“<”运算符是什么?
运算符“小于”在类上使用时具有特殊行为。如果一个类是其后代,则将其视为“小于”另一个类。
也许问的太多了,但是如果有人可以为此规范编写代码,那真的会对我有很大帮助。
我不会编写所有的实现,但这里是人们通常如何定义自定义异常类。
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
推荐阅读
- javascript - 如何在 nightmarejs 中将隐身模式更改为基本 chrome
- tags - 如何获取财务报表中显示的xbrl标签与名称的映射关系?
- mongodb - 从 mongo 集合中获取月份的最后一个条目
- c# - 具有 EntityFrameworkCore.SQlite 的应用程序未在选定机器上运行
- c++ - 递归函数,查找以 0 开头并具有 0 和 1 的奇数序列的长度为 N 的二进制字符串的数量
- sql-server - LINQPad 6 连接到 SQL Server 2019 Docker 在登录前握手时出错
- unity3d - 如何在不运行 build all Bundles 的情况下生成 AssetBundleManifest 文件?
- winapi - MFC:如何从主线程使用 MsgWaitForMultipleObjects() 来等待多个线程完成使用 SendMessage()?
- javascript - 使用 Alpine js 与 $dispatch 进行组件通信
- python - 如何使用可变列标题从数据框的一列中提取一组行?