【发布时间】:2016-08-06 14:58:25
【问题描述】:
我有一个 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
这样可以正常工作,但不使用根目录:
--- 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\":{}}"
【问题讨论】:
-
你为什么不使用这个?渲染 json:{类别:@category}
-
steady_daddy,我更新了我的问题
-
啊,我是个白痴。右括号应该在行尾。
-
steady_daddy,再次更新问题。使用
{ category: @category }它不使用序列化程序:( -
这里为什么需要序列化器?
标签: ruby-on-rails json unit-testing active-model-serializers