如何在Rails中编写JSON API的测试用例

时间:2018-09-03 08:07:10

标签: ruby-on-rails api rspec render

我已经为主题控制器编写了一个api,它将执行所有操作操作,我需要使用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

运行测试时,它会显示我在注释中提到的上述代码行的错误消息。

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

1 个答案:

答案 0 :(得分:0)

您可以测试控制器操作的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