我试图检查我的一个类方法是否响应无效输入有异常,但Rspec没有它.
我的班级文件:
class WhateverClass def run(options) if options['input'].nil? || options['input'].empty? fail ArgumentError, 'No input object provided in configuration.' end end end
我的Rspec测试:
RSpec.describe WhateverClass do it 'should raise an ArgumentError when provided invalid input' do invalid_input = { 'nonsense' => 'here' } expect(WhateverClass.new.run(invalid_input)).to raise_error(ArgumentError) end end
运行上述测试的结果如下:
1) WhateverClass should raise an ArgumentError when provided invalid input Failure/Error: expect(WhateverClass.new.run(invalid_input)).to raise_error(ArgumentError) ArgumentError: No input object provided in configuration. # ./whatever_class.rb:9:in `run' # ./spec/whatever_class_spec.rb:14:in `block (2 levels) in' Finished in 0.00048 seconds (files took 1.51 seconds to load) 1 example, 1 failure
================================================== =
请注意,如果我这样做:
RSpec.describe WhateverClass do it 'should raise an ArgumentError when provided invalid input' do expect{ fail ArgumentError }.to raise_error(ArgumentError) invalid_input = { 'nonsense' => 'here' } expect(WhateverClass.new.run(invalid_input)).to raise_error(ArgumentError) end end
第一个期望通过,但第二个预期失败.
如何使此测试正常运行?
事实证明,改变它:
expect(WhateverClass.new.run(invalid_input)).to raise_error(ArgumentError)
至:
expect { WhateverClass.new.run(invalid_input) }.to raise_error(ArgumentError)
解决了这个问题.希望这有助于其他人.