开发者

How can I test an action that handles exceptions using rack/test on Sinatra?

I want to test this route I made on Sinatra:

get '/party' do
  begin
    party_source.parties
  rescue Exceptions::SourceNotFoun开发者_如何学GodError
    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:

require 'sinatra/base'

class Hello < Sinatra::Base
  get '/party' do
    begin
      raise StandardError
    rescue StandardError
      status 404
    end
  end
end


Hello.run! if __FILE__ == $0

sinatra_test.rb:

$:.push('.')
require 'hello_sinatra'
require 'test/unit'
require 'rack/test'

ENV['RACK_ENV'] = 'test'

class HelloTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    Hello
  end

  def test_correct_status_code_when_get_error_404
    get '/party'
    assert_equal 404, last_response.status
  end
end

However, something looks strange in your code. Can you try to replace MyApp.party_source = source_404 with app.party_source = source_404

Update

You're only catching Exceptions::SourceNotFoundError and Exceptions::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 Exception and you will quickly see where the problem is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜