2017-08-02 205 views
-1

假设我有这样的方法的类:从造成的RSpec测试故障防止错误

class MyClass 
    ... 

    def self.some_class_method 
    my_instance = MyClass.new 
    self.other_class_method(my_instance) 
    raise 'ERROR' 
    end 

    def self.other_class_method(instance) 
    ... 
    end 
end 

而且测试它看起来像这样:

require 'spec_helper' 

describe MyClass do 
    describe '.some_class_method' do 
    context 'testing some_class_method' do 
     it 'calls other_class_method' do 
     MyClass.should_receive(:other_class_method) 

     MyClass.some_class_method 
     end 
    end 
    end 
end 

测试错误出与ERROR,如果我删除raise 'ERROR'行,测试通过。但在这里,我只想测试some_class_method是否调用other_class_method,而不管之后会发生什么。我可以改变它以期望该方法提出错误,但这不是此特定测试的目的。有没有更好的办法?

回答

1

您可以在测试中解救异常。

describe MyClass do 
    describe '.some_class_method' do 
    context 'testing some_class_method' do 
     it 'calls other_class_method' do 
     MyClass.should_receive(:other_class_method) 
     begin 
      MyClass.some_class_method 
     rescue 
     end 
     end 
    end 
    end 
end 
+0

谢谢,这个作品! – blacktrance

0

如何添加一个期望,该方法引发错误。这甚至会增强您的测试:

describe MyClass do 
    describe '.some_class_method' do 
    context 'testing some_class_method' do 
     it 'calls other_class_method' do 
     expect(MyClass).to receive(:other_class_method) 
     expect { MyClass.some_class_method }.to raise_error("ERROR") 
     end 
    end 
    end 
end 
+0

然后,如果方法停止引发错误,则测试将失败。无论错误是否发生,测试都应该通过,只关心被调用的other_class_method。 – blacktrance