This will be a rapid and simple article about how to test your GraphQL code in a Rails app with RSpec.
When it comes to Rails and GraphQL, one question that you could ask yourself is. How can I test my queries or mutations?
Should I send an HTTP request? It seems not necessary to do that; what you want is to test the logic of my GraphQL queries or mutations.
Do not worry. You don't have to.
How to test
Let's say you have a simple Schema with a Type called TestableType and a query that resolves testable, which has only a field called tested.
class TheSchema < GraphQL::Schema
class TestableType < GraphQL::Schema::Object
field :tested, String
end
class Query < GraphQL::Schema::Object
field :testable, [TestableType], null: true
def testable
{ name: "You can test me" }
end
end
query(Query)
end
To use graphql, you do not need any framework. You can define everything in the same file.
Now, for testing, we need to use the execute method of the schema. And the string of graphql query that I want to execute.
With what we did earlier, it would look like this if we use minitest.
class TestMeme < Minitest::Test
def setup
@query = <<-GQL
{
testable {
name
}
}
GQL
end
def test_that_kitty_can_eat
assert_equal TamereSchema.execute(@query).to_h.dig('data','testable'), {"name"=>"Pogo Stick"}
end
end
Conclusion
Now you know how to test your graphql queries without making HTTP requests.
I hope this post helped you to understand more about Ruby and GraphQL. When I began to use GraphQL with Ruby, this was one of the first questions I asked myself.
Here is a gist if you want to see it in action in a Ruby file: https://gist.github.com/Lucas-Barret/b3db09d231165703e5f31ba52487ec60
Top comments (0)