In the last article we added a few GraphQL mutations to our test application. It is time to create automated tests for each of them. But first things first, we need to set up RSpec in order to write better specs.
RSpec and FactoryBot
Installing Rspec and Factory Bot are trivial. First, you have to add those gems to your
and then run
rails generate rspec:install
The last thing I recommend to do is adding this line to
Thanks to that line we will be able to use shortened syntax for building and creating objects using factories. It means that instead of
FactoryBot.create(:book) we will be able to simply write
I mentioned that we will be able to create objects easily thanks to FactoryBot. But in order to have this possibility, we have to define those factories first. We need to create two of them:
Now we have everything in place and we are able to start writing specs. But please note that for now, we will cover only the happy paths.
During the creation of the object, the most important assertion we can write is checking if the object is created and its fields in the database are correct. But when we are testing GraphQL endpoint we also want to make sure that it returns the proper object. Knowing all that, let’s take a look at the final version of our test. Following the RSpec convention, we are going to save our file in
specs folder, in the same tree directory as the original file. In short, we save our spec in
As you can see, we test
.resolve method and we check the things that I mentioned earlier, so writing and returning the object. There are two separates specs and we want to use the same query for both of them. Because of that, we define the
query function when we pass the arguments that matter for us. In this case, we only need to pass
updateBook spec we are going to test if an object is changed after the operation and if the correct object is returned. The code will be really similar to the previous one and we place it in
The last spec will be written for
destroyBook mutation. We will focus on checking if the object is removed and if we return removed object after the action is finished. As you probably guessed, we save the code in
Writing the specs for GraphQL mutations isn’t that different from writing specs for the controller’s actions. The only difference might be defining the
query method. I highly encourage you to use
<<\~ to write a multiline query and increase the readability. Other than that, you simply have to focus on things and edge cases you want to cover in your specs. That’s all. Happy coding!
Need a hand in your Ruby on Rails development? Check out our team!