如何在 Rails Graphql 中对类型对象进行单元测试

问题描述 投票:0回答:1

我有一个 Rails graphQL API。 我正在努力寻找有关如何在不需要查询的情况下对我的自定义类型对象进行单元测试的文档。

比如我有这样的类型:

module Types
  class ScheduleType < ApplicationRecordType
    field :size, Integer, null: true
    field :default_fee_cents, Integer, null: true
    field :instructor_name, String, null: true
    field :confirmed_registrations_count, Integer, null: false
    field :program, ProgramType, null: false
    field :teacher, CurrentUserType, null: false
    field :events, [EventType], null: true
    field :registrations, [RegistrationType], null: true
    field :fee_structure, FeeStructureType, null: true
    field :available_spots, Integer, null: true
    field :status, String, null: true
    field :can_edit, Boolean, null: true

    # .. more stuff

    def can_edit
      !object.contains_registrations? 
    end

    def program
      Loaders::RecordLoader.for(Program).load(object.program_id)
    end

    def registrations
      authorize! object, to: :manage?

      Loaders::AssociationLoader.for(Schedule, :registrations).load(object)
    end

    def available_spots
      return if object.size.nil?

      [
        object.size - object.confirmed_registrations_count,
        0
      ].max
    end
  end
end

注意:

ApplicationRecordType < BaseObject
BaseObject < GraphQL::Schema::Object

我想单独测试这些方法。我很难相信我需要使用查询来测试这一点。这就像说我需要一个控制器测试才能对我的模型方法进行单元测试。但我还没有找到关于如何做到这一点的示例、精华或文档,所以我开始认为这不是一个好主意,或者我错过了一些东西。

ruby-on-rails graphql
1个回答
0
投票

现在 graphql 已将其添加到他们的文档中。它使用起来并不是非常简单(我们必须创建自己的共享上下文和匹配器以使其不那么冗长),但这正是我正在寻找的:

https://graphql-ruby.org/testing/helpers.html

# Mix in `run_graphql_field(...)` to run on `MySchema`
include GraphQL::Testing::Helpers.for(MySchema)

#Then, you can run fields using Testing::Helpers#run_graphql_field:
post = Post.first
graphql_post_title = run_graphql_field("Post.title", post)
assert_equal "100 Great Ideas", graphql_post_title
# Assuming `include GraphQL::Testing::Helpers.for(MySchema)`
# was used above ...
with_resolution_context(type: "Post", object: example_post, context: { current_user: author }) do |rc|
  assert_equal "100 Great Ideas", rc.run_graphql_field("title")
  assert_equal true, rc.run_graphql_field("viewerIsAuthor")
  assert_equal 5, rc.run_graphql_field("commentsCount")
  # Optionally, pass `arguments:` for the field:
  assert_equal 9, rc.run_graphql_field("commentsCount", arguments: { include_unmoderated: true })
end
© www.soinside.com 2019 - 2024. All rights reserved.