RSpec: How to write unit test case to receive an exception which is getting raised in private method

后端 未结 1 1835
名媛妹妹
名媛妹妹 2021-01-24 15:34

I have implemented Optimistic Locking for Race Condition. For that, I added an extra column lock_version in the Product. Method: recalculate is calling

相关标签:
1条回答
  • 2021-01-24 15:54

    You could write something like:

    expect(ActiveRecord::StaleObjectError).to receive(:new).and_call_original
    

    Because you are rescue-ing the exception

    Make sure to check https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers

    expect(car_v2).to receive(:method1).and_raise(ActiveRecord::StaleObjectError)
    

    Means that when car_v2 receives the method1 you won't call it but you'll raise an exception of type ActiveRecord::StaleObjectError. This is why you also receive the ArgumentError

    With rspec you can check that a specific code raises an error (that is not handled in your case it is handled -> rescue...) like this:

    expect { my_cool_method }.to raise_error(ErrorClass)
    
    0 讨论(0)
提交回复
热议问题