【问题标题】:How to write test cases for JSON API in rails [duplicate]如何在rails中为JSON API编写测试用例[重复]
【发布时间】: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 的状态,另外,使用stubstub 您的回复并与您的requestexpected response 进行比较。

标签: ruby-on-rails api rspec render


【解决方案1】:

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

【讨论】:

  • 代码中的 create_list 是什么意思
  • 如果要多次创建一个对象,同2.times {FactoryGirl.create(:topic)}
  • 当我运行你提供的测试时抛出错误“没有将字符串隐式转换为整数”
  • 哪一行?你能用错误更新你的 OP 吗?
  • OP是什么意思???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多