Skip to the content.

Home

Previous: Chapter 8 - The N


📝 As as app user, I want to create a new round, so that I can start the selection process.

We know that we create records through mutations and we’ve covered the topic before so this should be quick.

Generate a mutation.

Terminal

bin/rails g graphql:mutation_create Round

A mutation class named Mutations::RoundCreate is generated for us and a round_create field is added to Types::MutationType. We won’t need to make any changes to app/graphql/types/mutation_type.rb so let’s look at app/graphql/mutations/round_create.rb. We won’t need round_input so we’ll remove that. We’ve already got some generic error handling set up so we’ll use create! again, instead of save. We’re not anticipating any failures here anyway, but if it happens we’ll catch it.

Make those changes.

app/graphql/mutations/round_create.rb

module Mutations
  class RoundCreate < BaseMutation
    description "Creates a new round"

    field :round, Types::RoundType, null: false

    def resolve
      round = Round.create!
      { round: round }
    end
  end
end

Generate a new test.

Terminal

bin/rails g integration_test types/mutation_type/round_create

Fill in the generated test.

test/integration/types/mutation_type/round_create_test.rb

require "test_helper"

class Types::MutationType::RoundCreateTest < ActionDispatch::IntegrationTest
  setup do
    @query = <<~GRAPHQL
      mutation RoundCreate {
        roundCreate(input: {}) {
          round {
            id
            createdAt
            updatedAt
            selections {
              id
            }
          }
        }
      }
    GRAPHQL
  end

  test "round_create" do
    assert_difference -> { Round.count } do
      post graphql_path, params: { query: @query }

      round = Round.last

      assert_equal(
        {
          "data" => {
            "roundCreate" => {
              "round" => {
                "id" => round.id.to_s,
                "createdAt" => round.created_at.iso8601,
                "updatedAt" => round.updated_at.iso8601,
                "selections" => [],
              },
            },
          },
        },
        @response.parsed_body
      )
    end
  end
end

Run the new test.

Terminal

bin/rails t test/integration/types/mutation_type/round_create_test.rb

Check for regressions by running all tests.

Terminal

bin/rails t

Success!

âś… Make a commit

âś… As as app user, I want to create a new round, so that I can start the selection process.


Next: Chapter 10 - The Selection