ruby-on-rails - 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
解决方案
您可以测试您的控制器操作的 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
推荐阅读
- android - 可以在导航抽屉中加载布局吗?
- android - Okhttp 缓存文件未创建(不工作 okhttp 缓存)
- python - Python 的 ADT 优先级队列
- swift - 为什么迁移后 Realm 的架构版本会重置为 0?
- php - PHP array_sum 输出单个数字而不是整体
- typescript - 使用 Typescript 但没有 Webpack/ts-loader 的 Vue 类型检查
- python-3.x - os.path.join 在某些情况下给出不正确的输出
- python - 各种 python 安装的 pip3 列表
- java - 使用 Apache Camel 并行处理多个文件
- amazon-web-services - AWS Cognito 基于角色的授权