我的目标是在ruby中测试我的GraphQL模式的类型,我正在使用。
我找不到这方面的最佳实践,所以我想知道测试Schema的字段和类型的最佳方法是什么。
gem建议不要直接测试模式( http://graphql-ruby.org/schema/testing.html ),但我仍然认为能够知道模式意外更改的时间是很有价值的。
有这样一种类型:
module Types
class DeskType < GraphQL::Schema::Object
field :id, ID, 'Id of this Desk', null: false
field :location, String, 'Location of the Desk', null: false
field :custom_id, String, 'Human-readable unique identifier for this desk', null: false
end
end我的第一种方法是在GraphQL::Schema::Object类型中使用fields哈希,例如:
Types::DeskType.fields['location'].type.to_s => 'String!'创建一个RSpec匹配器,我可以想出如下所示的测试:
RSpec.describe Types::DeskType do
it 'has the expected schema fields' do
fields = {
'id': 'ID!',
'location': 'String!',
'customId': 'String!'
}
expect(described_class).to match_schema_fields(fields)
end
end但是,这种方法有一些缺点:
发布于 2018-07-06 14:31:37
它看起来您想测试您的模式,因为您想知道它是否会破坏客户端。基本上你应该避免这样做。
相反,您可以使用宝石(如:graphql-schema_comparator )打印破缺更改。
发布于 2018-07-06 04:12:42
与第一种方法相比,我感觉到的是对GraphQL模式使用快照测试的改进,而不是一个接一个地测试每种类型/突变模式,我创建了一个测试:
RSpec.describe MySchema do
it 'renders the full schema' do
schema = GraphQL::Schema::Printer.print_schema(MySchema)
expect(schema).to match_snapshot('schema')
end
end这种方法使用了rspec-快照 gem的稍微修改的版本请看我的公关。
gem不允许您使用一个命令更新快照,比如在Jest中,所以我还创建了一个rake任务来删除当前快照:
namespace :tests do
desc 'Deletes the schema snapshot'
task delete_schema_snapshot: :environment do
snapshot_path = Rails.root.join('spec', 'fixtures', 'snapshots', 'schema.snap')
File.delete(snapshot_path) if File.exist?(snapshot_path)
end
end这样,当模式被修改时,您将得到相当大的RSpec差异。
发布于 2018-07-06 14:09:21
顶层架构对象有一个#执行方法.您可以使用这个来编写测试,例如
RSpec.describe MySchema do
it 'fetches an object' do
id = 'Zm9vOjE'
query = <<~GRAPHQL
query GetObject($id: ID!) {
node(id: $id) { __typename id }
}
GRAPHQL
res = described_class.execute(
query,
variables: { id: id }
)
expect(res['errors']).to be_nil
expect(res['data']['node']['__typename']).to eq('Foo')
expect(res['data']['node']['id']).to eq(id)
end
end#execute方法的返回值将是传统的HTTP样式响应,作为字符串键式哈希。(实际上它是一个GraphQL::查询::结果,但它将大部分事情委托给一个嵌入式哈希。)
https://stackoverflow.com/questions/51202929
复制相似问题