2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rspecでGraphQLのresolverをテストする

Last updated at Posted at 2020-05-22

はじめに

graphqlのテストってみなさんどう書いてますか?
queryを定義してテストもできますが、少し面倒だど感じている今日この頃。
そこで、queryとかmutationに定義されているresolverをrspecでテストする方法について説明します。

mutationの例

例えば、以下のようなmutationを定義しているとしましょう。

mutation.rb
module Mutations
  class CreateUser < BaseMutation
    argument :id, ID, required: true
    field :user, ObjectTypes::UserType, null: false

    def resolve(id: nil)
      user = ::User.create!(id: id)
      {
        user: user
       }
    end
  end
end

単純ですが、idをもらってuserを作成するmutationです。
今回のテスト対象はこのresolveになります。

rspceを書く

ではさっそくrspecを書きたいと思います。

create_user_rspec.rb
require 'rails_helper'

RSpec.describe CreateUser, type: :request do
  describe 'resolver' do
    it 'userが作成されていること' do
      mutation = CreateUser.new(field: nil, object: nil, context:{})
      mutation.resolve(id: [作成するuser_id])
      expect(..).to eq ..
    end

まず、mutationのクラスであるCreateUserクラスのインスタンスを作成します。
引数のfieldとobjectは基本的にnullで良いと思います。
contextについては、場合によってはcurrent_userを入れることもできます。その場合は context:{current_user: User.first}となります。

contextを直接入れられるのが便利ですよね。
そして、作成したmutationのresolveメソッドを読んであげればテスト上で定義したresolve内の処理が実行されます。
これだと、graphqlのテストがかなり楽にかけます!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?