【发布时间】:2018-09-03 17:32:21
【问题描述】:
我已经为主题控制器编写了一个 api,它将执行所有的 crud 操作。我需要使用 Rspec 测试 api。对于索引操作,我已经为 http 状态编写了一个测试用例。此外,我需要检查索引页面是否正确呈现。索引操作的主题 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
运行测试时,它会显示我在 cmets 中提到的上述代码行的错误消息。
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
【问题讨论】:
-
您不应该在控制器呈现
json响应时测试您的views。您应该检查response的状态,另外,使用stub到stub您的回复并与您的request和expected response进行比较。
标签: ruby-on-rails api rspec render