我有一个测试,我需要为其编写代码以使其通过。 测试是这样的:
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/