TIL: Asserting Exceptions with Cucumber & Ruby
Proper use of Cucumber follows a strict given-when-then syntax. This posses a small problem when trying to assert an exception in a 'then' step if it is raised in a 'when' step.
Proper use of Cucumber follows a strict given-when-then syntax. This posses a small problem when trying to assert an exception in a 'then' step if it is raised in a 'when' step.
For instance, suppose I have some gherkin that looks like this:
When I do something unwanted
Then an exception is raised
The problem here is that I have to do something with the exception in the 'when' step. I could catch the exception and deal with it in the 'then' like so:
When('I do something unwanted') do
begin
raise 'something bad'
rescue => e
@excepton = e
end
end
Then('an exception is raised') do
expect(@exception).not_to be_nil
end
That's gross. Let's do this better by deferring the action with lambdas (and by using a state variable wrapper)
When('I do something unwanted') do
artefacts.request = -> { make_a_dangerous_call }
end
Then('an exception is raised') do
expect { artefacts.request.call }.to raise_exception
end
Much neater.
Member discussion