使Ruby中的rspec测试通过

时间:2018-07-18 15:18:52

标签: 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

1 个答案:

答案 0 :(得分:1)

  

在测试中,我有FEBRUARY= 0xFFFFFFFF。我不明白这句话的意思。

这意味着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
相关问题