Asserting that a particular exception is thrown in Cucumber

前端 未结 4 1747
北海茫月
北海茫月 2021-02-02 13:20

Scenario

I\'m writing a library (no Ruby on Rails) for which I\'d like to have very detailed Cucumber features. This especially includes describing erro

4条回答
  •  孤城傲影
    2021-02-02 13:50

    I thought about it once more, and maybe the answer is:

    There is no elegant solution, because the Given-When-Then-Scheme is violated in your case. You expect that "Then an exception should be thrown" is the outcome of "When I do something unwanted".

    But when you think about it, this is not true! The exception is not the outcome of this action, in fact the exception just shows that the "When"-Statement failed.

    My solution to this would be to test at a higher level:

    When I do something unwanted
    Then an error should be logged
    

    or

    When I do something unwanted
    Then the user should get an error message
    

    or

    When I do something unwanted
    Then the program should be locked in state "error"
    

    or a combination of these.

    Then you would "cache the exception" in your program - which makes perfect sense, as you most likely need to do that anyway.

    The two problems you've stated would be solved, too.

    In case you really must test for exceptions

    Well, i guess then cucumber isn't the right test suite, hmm? ;-)

    As the Given-When-Then-Scheme is violated anyway, I would simply write

    When I do something unwanted it should fail with "ArgumentError"
    

    and in the step definitions something like (untested, please correct me if you try it)

    When /^I do something unwanted it should fail with "(.*)"$/ do |errorstring|
      expect {
        throw_an_exception!
      }.to raise_error(errorstring)
    end
    

    As said above, that is horribly wrong as the scheme is broken, but it would serve the purpose, wouldn't it? ;-)

    You'll find further documentation at testing errors at rspec expectations.

提交回复
热议问题