简体   繁体   中英

rails api testing json response

I have a 4.2.5 rails api and I guess I get this error thanks to the extracted responders. What should I change to make it work?

error:

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>'

controller

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

Test

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

UPDATE:

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

This way it's working, but the root is not used:

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

UPDATE2:

With the following code it doesn't use active model serializer:

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\":{}}"

Loooks like you made a http request, either add the header Content-Type = application/json to request when you call or change your controller code as below to make it working

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

Hope this will help you

It seems from your code that you are using active model serializers incorrectly. This Railcast and this sitepoint.com article explains how you should properly use serializers in Rails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM