【问题标题】:Why "assert_response" ignores the custom message in Rails?为什么“assert_response”会忽略 Rails 中的自定义消息?
【发布时间】:2012-07-12 11:42:36
【问题描述】:

在我的功能测试中,我像这样验证响应状态:

assert_response :error, "My error message"

但是,Rails 会忽略我的自定义消息和报告:

预期的响应是 <:error>,但实际上是

有什么想法吗?

我使用 Rails 3.2.6。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 functional-testing


    【解决方案1】:

    我也在想同样的事情。原来它已在 Github 上修复:https://github.com/rails/rails/commit/d28a15ede59f6434f1b7a8d01be060fa73b4746c

    对我来说,将 rails/actionpack gem 更新到最新版本并未包含该修复,但我能够手动更新 response.rb。它位于:

    /Users/alex/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_dispatch/testing/assertions/response.rb
    

    【讨论】:

      【解决方案2】:

      在您的测试中,您提到响应类型为 :error,它与状态码 500-599 匹配。但是由于您的测试返回状态代码 201,它无法匹配该状态代码并根据 assert_response 的定义显示消息

      def assert_response(type, message = nil)
          clean_backtrace do
            if [ :success, :missing, :redirect, :error ].include?(type) && @response.send("#{type}?")
              assert_block("") { true } # to count the assertion
            elsif type.is_a?(Fixnum) && @response.response_code == type
              assert_block("") { true } # to count the assertion
            else
              assert_block(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code)) { false }
            end               
          end
      end
      

      由于类型和状态码不匹配,它进入 else 并给出该消息。

      以下是响应类型及其匹配代码:

      :success: Status code was 200
      :redirect: Status code was in the 300-399 range
      :missing: Status code was 404
      :error: Status code was in the 500-599 range
      

      【讨论】:

      猜你喜欢
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2019-08-31
      相关资源
      最近更新 更多