【问题标题】:Rails App with Sinatra engine - How to avoid rails errors?带有 Sinatra 引擎的 Rails 应用程序 - 如何避免 rails 错误?
【发布时间】:2015-12-30 19:19:09
【问题描述】:

问题:运行规范时,输出非常混乱,而不是说明错误在哪里,它只会引发误导性错误

这是在 rails lib 文件夹中,它被挂载在 routes.rb 上

# lib/engines/users/app.rb

module Engines
  module Users
    class App < Sinatra::Base
        get '/api/v1/users/me' do
          raise 'runtime error here'
        end

        get '/api/v1/another-route' do
          # something here
          status 200
        end
    end
  end
end

spec 文件如下所示:

it 'returns a 200' do
  get '/api/v1/users/me', auth_attributes
  expect(last_response.body).to eq 'something' # added to clarify my point, it's not the response status that I care of.
  expect(last_response.status).to be 200
end

错误:

 Failure/Error: expect(last_response.status).to be 200

   expected #<Fixnum:401> => 200
        got #<Fixnum:1001> => 500

   Compared using equal?, which compares object identity,
   but expected and actual are not the same object. Use
   `expect(actual).to eq(expected)` if you don't care about
   object identity in this example.

预期错误:

     RuntimeError:
       runtime error here

另一条路线也失败了:

it 'something' do
  get '/api/v1/another-route', auth_attributes
  expect(last_response.status).to be 401
  json = JSON.parse(last_response.body).with_indifferent_access
  expect(json[:message]).to eql "You have been revoked access."
end

错误:打印大量 html 输出,我认为这是 rails backtrace html 输出

预期错误:无,因为此端点不会引发错误

我的问题是是否有办法:

  1. 停止 rails 处理这个,所以它给出了实际的输出
  2. 避免由于一条路由引发异常而导致整个引擎失败

我相信通过解决第一点,第二点也会得到解决。

感谢您的宝贵时间

【问题讨论】:

  • get '/api/v1/users/me' 转到raise 'runtime error here',这将是一个内部服务器错误。这将给出 500 的响应状态,这是你得到的。
  • 在一个 vanilla sinatra 应用程序中,它实际上会返回`RuntimeError: runtime error here`
  • 但是您的规范正在查看状态代码。如果我复制您的 sinatra 代码并在 chrome 中转到它,查看标题我得到状态代码 500。您没有检查正文,它输出 RuntimeError
  • 我忘了补充,但你明白了。我已经更新了代码,所以现在应该很清楚了。
  • 恐怕这仍然令人困惑。您仍然有错误,因为它期望 200,但它返回 500。根据您更新的 sn-p expect(last_response.body).to eq 'something' 这通过了。如果这是您的测试所期望的,那么您不会得到预期的错误,它只会通过测试。

标签: ruby-on-rails ruby ruby-on-rails-4 sinatra rails-engines


【解决方案1】:

为了解决我的问题,我发现在spec_helper 上没有设置ENV['RACK_ENV'],将其设置为test 可以解决问题并引发我需要调试代码的异常。

这是因为https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1832

set :show_exceptions, Proc.new { development? }

development? 返回 true 而实际上应该为 false(需要将 RACK_ENV 设置为测试)

现在我得到了正确的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    相关资源
    最近更新 更多