ash*_*rus 4 testing rspec ruby-on-rails
我有一个 Rails API 应用程序,它非常大,并且有很多端点供用户访问数据。
我不确定如何创建将由每个开发人员执行的测试,以便将生产中出现错误的机会降至最低。
每个 API 根据他们的角色对不同类型的用户进行身份验证,并在其上呈现不同的 JSON。
首先,我认为您需要定义要测试的内容,例如
您说每个 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.
Run Code Online (Sandbox Code Playgroud)
在此之后,您可以开始检查您的请求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
Run Code Online (Sandbox Code Playgroud)
希望能给你一些指导
| 归档时间: |
|
| 查看次数: |
1970 次 |
| 最近记录: |