我正在构建一个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是什么以及如何操作它。
发布于 2020-04-30 21:21:38
你正在寻找Ruby 2.3中引入的squiggly for。它就像一个普通的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 https://stackoverflow.com/questions/61524296
复制相似问题