如何在 rails 中为 JSON API 编写测试用例
How to write test cases for JSON API in rails
我已经为主题控制器编写了一个 api,它将完成所有 operations.I 需要使用 Rspec 测试 api 的工作。对于索引操作,我已经为 http status.Further 编写了一个测试用例,我需要检查索引页面呈现的天气 correctly.Topic Api 索引操作的控制器是这样的:
class Api::V1::TopicsController < ApplicationController
def index
@topics = Topic.all
render json: @topics,status: 200
end
end
Rspec 对于主题控制器索引操作是:
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
当 运行 测试显示我在评论中提到的上述代码行的错误消息时。
Api::V1::TopicsController GET #index returns http success
Failure/Error: expect(response).to render_template(:index)
expecting <"index"> but rendering with <[]>
如何解决?
错误:
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
我已经为主题控制器编写了一个 api,它将完成所有 operations.I 需要使用 Rspec 测试 api 的工作。对于索引操作,我已经为 http status.Further 编写了一个测试用例,我需要检查索引页面呈现的天气 correctly.Topic Api 索引操作的控制器是这样的:
class Api::V1::TopicsController < ApplicationController
def index
@topics = Topic.all
render json: @topics,status: 200
end
end
Rspec 对于主题控制器索引操作是:
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
当 运行 测试显示我在评论中提到的上述代码行的错误消息时。
Api::V1::TopicsController GET #index returns http success
Failure/Error: expect(response).to render_template(:index)
expecting <"index"> but rendering with <[]>
如何解决? 错误:
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