A repost of my past article on Medium (2023).
One day my father asked me to find a good Cypress API Test Script example and do a quick conversion to Ruby. (you will find out why in his upcoming article)
My first thought, “Cypress, isn’t it for web testing?” I did a Google search, indeed, there are plenty of articles on this topic. In fact, according to Cypress’ own LinkedIn post, Cypress API testing has a considerable audience.
There are seem some people “seriously” doing API Testing with Cypress, a web testing tool. I find it hard to comprehend.
To be fair (for comparision), I will use a Cypress API Test example (created by a credible source) in this Circle CI article: Testing an API with Cypress.
There are three files:
Configuration (cypress.json):
{
"baseUrl": "https://aqueous-brook-60480.herokuapp.com",
"integrationFolder": "cypress/integration/api-tests"
}
2. Package setup (package.json)
"scripts": {
"test": "cypress open"
},
3. Cypress Test Script (todo.spec.js):
describe('TODO api testing', () => {
let todoItem;
it('fetches Todo items - GET', () => {
cy.request('/todos/').as('todoRequest');
cy.get('@todoRequest').then(todos => {
todoItem = todos.body[0]['_id']
expect(todos.status).to.eq(200);
assert.isArray(todos.body, 'Todos Response is an array')
});
});
it('deletes Todo items - DELETE', () => {
cy.request('DELETE', `/todos/${todoItem}`).as('todoRequest');
cy.get('@todoRequest').then(todos => {
expect(todos.status).to.eq(200);
assert.isString(todos.body, 'todo deleted!')
});
});
it('Adds Todo item - POST', () => {
cy.request('POST', '/todos/', { task: "run tests" }).as('todoRequest');
// adds new Todo item by defining Todo name
cy.get('@todoRequest').then(todos => {
expect(todos.status).to.eq(200);
cy.wrap(todos.body).should('deep.include', {
task: 'run tests',
completed: false,
});
});
});
});
Basically, a typical CRUD type API test script, with HTTP GET, POST and DELETE methods.
The Ruby version is simpler and better
First of all, API testing for any website is all about HTTP Request and Response, which can be done in any programming language. This website is developed using React JS, I could test with with the wonderful Ruby language (Web or API).
For this simple test, I have little opportunity to show off Ruby’s shining ability to text processing, which are essential for complex API test cases.
FYI, Ruby is also “the most in-demand skill”, according to Hired’s 2023 State of Software Engineers Report.
Below is the equivalent API test script with Rest-Client, an HTTP and REST client for Ruby. The syntax framework is RSpec.
Keep reading with a 7-day free trial
Subscribe to The Agile Way to keep reading this post and get 7 days of free access to the full post archives.