rails api 测试 json 响应

rails api testing json response

我有一个 4.2.5 rails api 我想我得到这个错误要归功于提取的响应者。我应该更改什么才能使其正常工作?

错误:

1) Error:
Api::V1::GraphControllerTest#test_should_get_show:
ActionController::UnknownFormat: ActionController::UnknownFormat
    app/controllers/api/v1/graph_controller.rb:7:in `show'
    test/controllers/api/v1/graph_controller_test.rb:5:in `block in <class:GraphControllerTest>'

控制器

class Api::V1::CategoryController < ApplicationController
  def show
    category = params[:category] || "sports"
    @category = Category.where(cat_title: category.capitalize).first
    respond_to do |format|
      format.json { render json: @category, serializer: CategorySerializer, root: "category" }
    end
  end
end

测试

require 'test_helper'

class Api::V1::CategoryControllerTest < ActionController::TestCase
  test "should get show" do 
    get :show, {'category' => 'science'}, format: :json
    assert_response :success
    assert_equal "{\"category\":{\"title\":\"science\",\"sub_categories\":1}}", @response.body
  end
end

更新:

class Api::V1::CategoryController < ApplicationController
  def show
    category = params[:category] || "sports"
    @category = Category.where(cat_title: category.capitalize).first
    render json: @category, serializer: CategorySerializer, root: "category"
  end
end

这种方式可以工作,但未使用 root:

--- expected
+++ actual
@@ -1 +1 @@
-"{\"category\":{\"title\":\"science\",\"sub_categories\":1}}"
+"{\"title\":\"science\",\"sub_categories\":1}"

更新 2:

对于以下代码,它不使用活动模型序列化程序:

render json: { category: @category , serializer: CategorySerializer }

-"{\"category\":{\"title\":\"science\",\"sub_categories\":1}}"
+"{\"category\":    {\"cat_id\":2,\"cat_title\":\"Science\",\"cat_pages\":1,\"cat_subcats\":1,\"cat_files\":1,\"created_at\":\"2016-08-06T15:35:29.000Z\",\"updated_at\":\"2016-08-06T15:35:29.000Z\"},\"serializer\":{}}"

看起来您发出了 http 请求,请在调用时添加 header Content-Type = application/json 请求,或者如下更改您的控制器代码以使其正常工作

class Api::V1::CategoryController < ApplicationController
  def show
    category = params[:category] || "sports"
    @category = Category.where(cat_title: category.capitalize).first
    render json: { category: @category }
  end
end

希望对您有所帮助

从您的代码看来,您使用的活动模型序列化程序不正确。 This Railcast and this sitepoint.com 文章解释了您应该如何在 Rails 中正确使用序列化程序。