I want to test this route I made on Sinatra:
get '/party' do
begin
party_source.parties
rescue Exceptions::SourceNotFoundError
status 404
rescue Exceptions::SourceInternalError
status 503
end
end
And I wrote this test (assume the party_source is accessible by the test, in the actual code it is):
require 'rack/test'
def test_correct_status_code_when_get_error_404
source_404 = mock()
source_404.expects(:parties).with(nil).raises(Exceptions::SourceNotFoundError)
MyApp.party_source = source_404
get '/party'
assert_equal 404, last_response.status
end
When I run this test it fails because instead of getting 404 (my code) I get a status 500. No matter what exception I raise I always get and status 500, which I think is being generated by Sinatra or Rack.
How can I test this case?
Update
As I can understand it, the exceptions isn’t getting caught by my rescues blocks. Rack or Sinatra is getting it and handling the HTTP Status 500 response message.
I can’t understand how my rescue code block is being ignored.
Here’s a short example, showing that you can test such an action:
hello_sinatra.rb:sinatra_test.rb:However, something looks strange in your code. Can you try to replace
MyApp.party_source = source_404withapp.party_source = source_404Update
You’re only catching
Exceptions::SourceNotFoundErrorandExceptions::SourceInternalError, something else is likely going wrong in your mock, which gives the 500 error.Add a catchall at the end of your begin/rescue block using
rescue Exceptionand you will quickly see where the problem is.