Testing GraphQL-Ruby Mutations With RSpec

RJ Robinson
2 min readApr 5, 2019
Photo by Chris Murray on Unsplash

To start with, a little OpEd on how much I love working with GraphQL. I started tinkering with it about a year ago, and have since completed a project at work where we did a rewrite, an the results have been amazing. Pros and cons aside however, I needed a way to test.

This might not be the best solution for you, but this is what had worked on my team, and for our use case.
The tests needed to cover a few aspects. Did the user have access? We use our own Pundit hack. Were the proper arguments sent? And did the response come back as expected? This sounds like a basic controller test, so from there I treated it as such.

Usually, in an RSpec controller test, we have a #get or a #post method that allows us to interact with that endpoint, and I wanted to continue with that pattern. These usually return a #response object with everything we would want to test.

Once I defined the #query and #mutation methods, passing in the arguments were easy.

Say we have a simple book application, and we want to create a new book.
Below are the tests, and while this seems very basic, I hope it's clear enough to understand the ideas behind it.

Why did I decide to do it this way? A few reasons. One, I wanted to treat the mutation like any other post request. Data goes in, data comes out. I see a lot of tests trying to do some crazy things just to hit the resolver inside their mutation. I don’t really think that’s needed. Using the existing interface with the GraphQL Schema should test what you need to. Hope this helps, and I how you provide some feedback. I would love to see how everyone else tests. I can be found on twitter.

--

--

RJ Robinson

A Sr. Engineer at Code Climate & aspiring blogger. Passionate coder by day, meme creator by night. Expect tech talk & dad jokes on his blog.