I have a Rails API application which is quite big and have so many endpoints for users to access the data.
I'm not sure how to create tests which will be performed by every developer so that the chances of a bug in production are minimal.
Every API is authenticated to a different type of users based on their roles and renders different JSON on that.
First of all I think you need to define what do you want to test, example
You said every API is authenticate users based on their roles, so how do you authenticate this users? Basic-authentication, auth-token?
Lets create a scenario
First test the status code for the end-points
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.
After this you can start checking the response body for your requests GET
, POST
, PUT
, DELETE
and check if the content that you expect on the response is right.
Then write some integration tests for your API
Your can use RSpec
combined with frameworks like FactoryGirl
to write integrations tests to your api easier
# 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
Hope it give you some directions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With