Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Rails API application?

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.

like image 771
ashusvirus Avatar asked Mar 07 '23 12:03

ashusvirus


1 Answers

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

like image 171
ferbass Avatar answered Mar 12 '23 06:03

ferbass