Testing GraphQL APIs

Write calls in GraphQL Playground, then transform them into test scripts in Ruby.

Zhimin Zhan
7 min readNov 21, 2022

--

A repost of my daughter’s article with permission. I added a few notes. You can find more examples like this in my book: API Testing Recipes in Ruby.

GraphQL is an open-source data query and manipulation language for APIs and a runtime for fulfilling queries with existing data. It stores data in a graph-like structure.

This article will go through some common GraphQL API tests.

How I write GraphQL tests:

Most GraphQL endpoints provide a convenient and user-friendly interface (called Playground) to try out queries: you can type requests and get response data on the right. You can also view the schema there.

Screenshot of GraphQL Playground for Trevor Blades’ Countries API

I follow the steps:

  1. Try out queries in GraphQL Playground.
  2. I also may do it in an HTTP graphic tool that offers more features.
  3. By then, I have a good idea of the query request I’m sending and what kind of response data I expect.
  4. Write an automated test in RSpec.
    Invoking the GraphQL endpoint code is common. The majority of the effort is to parse response data and perform assertions. Ruby is a great language for that.
  5. Run, verify and refine (typically, I do this using TestWise).

When my test suite reaches a certain size, I run them in a Continuous Testing server, such as BuildWise.

I will use Trevor Blade’s public Countries API (endpoint: https://countries.trevorblades.com/) for some of the exercises in this article.

LIST all records

GraphQL Query

query is a GraphQL command to find matching data (list). The example below gets countries and returns the code and name back.

query { 
countries {
code
name
}
}

You can run this query in the GraphQL Playground, like below:

--

--

Zhimin Zhan

Test automation & CT coach, author, speaker and award-winning software developer. Help teams succeed with Agile/DevOps by implementing real Continuous Testing.