首页 > 解决方案 > 在 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 和“<”运算符是什么?

标签: rubytestingrspec

解决方案


在测试中我有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

推荐阅读