首页 > 解决方案 > How to write test cases for JSON API in rails

问题描述

I have written an api for topics controller which will do all the crud operations.I need to test the api using Rspec. For the index action i have written a test case for http status.Further i need to check weather the index page is rendered correctly.Topic Api controller for index action is like this:

class Api::V1::TopicsController < ApplicationController
  def index
    @topics = Topic.all
    render json: @topics,status: 200
  end
end

Rspec for topic controller index action is:

RSpec.describe Api::V1::TopicsController do
describe "GET #index" do
before do
  get :index
end
it "returns http success" do
  expect(response).to have_http_status(:success)
  ////expect(response).to render_template(:index)
end
end
end

When run the testing it showing error message for the above line of code that i mentioned in comments.

Api::V1::TopicsController GET #index returns http success
 Failure/Error: expect(response).to render_template(:index)
   expecting <"index"> but rendering with <[]>

How to resolve it? error:

  TypeError: no implicit conversion of String into Integer

0) Api::V1::TopicsController GET #index should return all the topics
   Failure/Error: expect(response_body['topics'].length).to eq(2)

   TypeError:
   no implicit conversion of String into Integer

标签: ruby-on-railsapirspecrender

解决方案


您可以测试您的控制器操作的 API 响应,这只是您index操作的参考。

describe TopicsController do

  describe "GET 'index' " do

    it "should return a successful response" do
      get :index, format: :json
      expect(response).to be_success
      expect(response.status).to eq(200)
    end

    it "should return all the topics" do
      FactoryGirl.create_list(:topic, 2)
      get :index, format: :json
      expect(assigns[:topics].size).to eq 2
    end

  end

end

推荐阅读