我正在构建一个rspec助手来测试我的graphql请求。
到目前为止,这是我的助手:
def mutation_params(name, attributes:, return_types:)
{
query:
<<~GQL
mutation {
#{name}(
input: { attributes: #{attributes} })
#{return_types}
}
GQL
}
end
并且我必须像这样声明attributes
:
let(:attributes) do
<<~GQL
{
email: "#{email_param}",
password: "#{password_param}"
}
GQL
end
现在,我想知道我该怎么做才能简单地将我的arguments
作为哈希传递,并让mutations_params
方法通过对该哈希进行迭代来构建GQL。
let(:attributes) do
{
email: email_param,
password: password_param
}
end
类似的东西:
def mutation_params(name, attributes:, return_types)
gql_attributes = <<~GQL
{
}
GQL
attributes.each do |key, value|
gql_attributes merge with
<<~GQL
"#{key}": "#{value}"
GQL
end
{
query:
<<~GQL
mutation {
#{name}(
input: { attributes: #{gql_attributes} })
#{return_types}
}
GQL
}
end
但是显然不起作用。我认为我的问题是我不太了解<<~GQL
是什么以及如何操作它。
答案 0 :(得分:1)
您正在寻找在Ruby 2.3中引入的弯曲的Heredoc。就像普通的heredoc一样,但是省略了前导缩进。 https://ruby-doc.org/core-2.5.0/doc/syntax/literals_rdoc.html
换句话说,它只是一个字符串! GQL位是任意的,但是传达heredoc目的的一种好方法。
您可以编写这样的帮助程序,将哈希值转换为GraphQL字符串
def hash_to_mutation(hash)
attr_gql_str = attributes.map{|k,v| "#{k}: #{v.inspect}"}.join(", ")
" { #{attr_gql_str} } "
end
然后假设属性是哈希,就像您在示例中一样
def mutation_params(name, attributes:, return_types:)
{
query:
<<~GQL
mutation {
#{name}(
input: { attributes: #{hash_to_gql(attributes)} })
#{return_types}
}
GQL
}
end