为自定义错误类设置默认消息

时间:2015-08-23 13:56:29

标签: ruby rspec

我创建了一个名为MyError的自定义错误类和一个名为MyClass的单独类,它在类方法self.raiser中引发了此错误。我还创建了rspec期望测试MyError被引发并且MyError打印消息my error

class MyError < StandardError
    def self.message
        'my error'
    end
end

class MyClass
    def self.raiser
        raise MyError
    end
end

describe MyClass do
    specify{ expect{ MyClass.raiser }.to raise_exception 'my error' }
    specify{ expect{ MyClass.raiser }.to raise_exception MyError }
end

这是我运行rspec时会发生什么:

$ rspec spec/raise_error.rb --format documentation

MyClass
  should raise Exception with "my error" (FAILED - 1)
  should raise MyError

Failures:

  1) MyClass should raise Exception with "my error"
     Failure/Error: specify{ expect{ MyClass.raiser }.to raise_exception 'my error' }
       expected Exception with "my error", got #<MyError: MyError> with backtrace:
         # ./spec/raise_error.rb:9:in `raiser'
         # ./spec/raise_error.rb:14:in `block (3 levels) in <top (required)>'
         # ./spec/raise_error.rb:14:in `block (2 levels) in <top (required)>'
     # ./spec/raise_error.rb:14:in `block (2 levels) in <top (required)>'

Finished in 0.01662 seconds (files took 0.08321 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/raise_error.rb:14 # MyClass should raise Exception with "my error"

这两个期望都应该通过。 got #<MyError: MyError>很奇怪,完全没有任何意义。它应该是got #<MyError: "my error">

另外,我认为这不是一个rspec错误:

2.2.1 :007 >   require 'rspec'
 => true 
2.2.1 :008 > require_relative 'spec/raise_error.rb'
 => true 
2.2.1 :009 > MyClass.raiser
MyError: MyError

1 个答案:

答案 0 :(得分:1)

您必须将方法message定义为实例方法,而不是您尝试的类方法。

我重写了自定义错误类:

class MyError < StandardError
  def message
    'my error'
  end
end

class MyClass
  def self.raiser
    raise MyError
  end
end

这是我的spec文件:

require_relative "../a.rb"

describe MyClass do
  it 'expects the Error class message' do
    expect { MyClass.raiser }.to raise_exception 'my error'
  end

  it 'expects the Error class name' do
    expect { MyClass.raiser }.to raise_exception MyError
  end
end

让我们运行规范:

[arup@Ruby]$ rspec -fd spec/a_spec.rb

MyClass
  expects the Error class message
  expects the Error class name

Finished in 0.00232 seconds (files took 0.16898 seconds to load)
2 examples, 0 failures