Ruby on rails 如何在rails中编写JSON API的测试用例
我已经为topics controller编写了一个api,它将执行所有crud操作。我需要使用Rspec测试api。对于索引操作,我编写了http状态的测试用例。此外,我需要检查索引页是否正确呈现。索引操作的主题Api控制器如下:Ruby on rails 如何在rails中编写JSON API的测试用例,ruby-on-rails,api,rspec,render,Ruby On Rails,Api,Rspec,Render,我已经为topics controller编写了一个api,它将执行所有crud操作。我需要使用Rspec测试api。对于索引操作,我编写了http状态的测试用例。此外,我需要检查索引页是否正确呈现。索引操作的主题Api控制器如下: class Api::V1::TopicsController < ApplicationController def index @topics = Topic.all render json: @topics,status: 200
class Api::V1::TopicsController < ApplicationController
def index
@topics = Topic.all
render json: @topics,status: 200
end
end
当运行测试时,它会显示我在注释中提到的上述代码行的错误消息
Api::V1::TopicsController GET #index returns http success
Failure/Error: expect(response).to render_template(:index)
expecting <"index"> but rendering with <[]>
您可以测试控制器操作的API响应,只是
索引
操作的参考
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
当控制器呈现
json
响应时,您不应该测试视图。您应该检查response
状态,同时,使用stub
来stub
您的响应,并与请求
和预期响应
进行比较。在代码中创建列表意味着什么如果您想多次创建对象,它与2.times{FactoryGirl.create相同(:topic)}
当我运行您提供的测试时抛出错误“无隐式转换字符串为整数”哪一行?您能用错误更新OP吗?OP的意思是什么???
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
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