【发布时间】:2018-04-03 06:14:04
【问题描述】:
我有一个相当大的 Rails API 应用程序,有很多端点供用户访问数据。
我不确定如何创建将由每个开发人员执行的测试,以便将生产中出现错误的可能性降至最低。
每个 API 都根据不同类型的用户的角色进行身份验证,并在其上呈现不同的 JSON。
【问题讨论】:
标签: ruby-on-rails testing rspec
我有一个相当大的 Rails API 应用程序,有很多端点供用户访问数据。
我不确定如何创建将由每个开发人员执行的测试,以便将生产中出现错误的可能性降至最低。
每个 API 都根据不同类型的用户的角色进行身份验证,并在其上呈现不同的 JSON。
【问题讨论】:
标签: ruby-on-rails testing rspec
首先我认为你需要定义你想测试什么,例如
您说每个 API 都会根据角色对用户进行身份验证,那么您如何对这些用户进行身份验证?基本身份验证,身份验证令牌?
让我们创建一个场景
首先测试端点的状态码
200: OK - Basically self-explanitory, the request went okay.
401: Unauthorized - Authentication credentials were invalid.
403: Forbidden
- The resource requested is not accessible - in a Rails app, this would generally be based on permissions.
404: Not Found - The resource doesn’t exist on the server.
在此之后,您可以开始检查您的请求GET、POST、PUT、DELETE 的响应正文,并检查您期望的响应内容是否正确。
然后为你的 API 编写一些集成测试
您可以使用RSpec 结合FactoryGirl 等框架更轻松地为您的api 编写集成测试
# spec/api/v1/user_spec.rb
describe "sample API" do
it 'should return a valid user' do
user = FactoryGirl.create(:user)
get "/api/v1/user/#{user.id}"
# test for the 200 status-code
expect(response).to be_success
# check that the message attributes are the same.
expect(json['name']).to eq(user.name)
end
end
希望能给你一些指导
【讨论】: