用于用户登录的GraphQL API单元测试



我需要为使用RubyonRails和GraphQL API的应用程序的登录用户编写一个单元测试。在Altair上,当执行signIn突变时,我需要将服务器URL设置为环境变量,然后发送POST请求以使突变生效。我正在尝试做同样的事情,只是在一个单元测试文件中。这是我的突变文件:

module Mutations
class SignInUser < BaseMutation
argument :auth, Types::AuthProviderEmailInput, required: false
field :token, String, null: true
field :user, Types::UserType, null: true
def resolve(auth: nil)
# basic validation
return unless auth
user = User.where('uuid=? OR email=?', auth[:user_id], auth[:user_id]).first()
# ensures we have the correct user
return unless user && user.is_active
return unless user.authenticate(auth[:password])
user.update_attributes(invitation_status: true) if !user.invitation_status
{ user: user, token: AuthToken.token(user) }
end
end
end

这是我的测试文件:

require 'test_helper'
class Mutations::SignInUserTest < ActionDispatch::IntegrationTest
def perform(args = {})
Mutations::SignInUser.new(object: nil, field: nil, context: {}).resolve(args)
end
test 'sign in user' do
post "serverurl.com"
user = perform(
auth: {
user_id: "example",
password: "example"
}
)
assert user.persisted?
end
end

POST请求似乎可以工作,因为它没有返回任何错误,但user返回null。我想这是因为我的POST请求和我实际登录时的用户是分开的,所以突变不起作用。我试着只发送POST请求,puts response.body是这样的:

post "serverurl.com"
puts response.body

这给了我一个消息说CCD_ 3。这让我觉得我必须在其参数或其他内容中发送突变和POST请求,所以我尝试使用:

post "serverurl.com", params: { signInUser: { input: { auth: user_id: "example", password: "example" } } }

但这只是在最后给了我一堆} } }的语法错误,我不知道为什么。我不知道还能在这里尝试什么,所以如果能提供一些帮助,我将不胜感激。

GraphQL查询是字符串,其变量是JSON编码的。你的例子:

post "serverurl.com", params: { signInUser: { input: { auth: user_id: "example", password: "example" } } }

可能需要更像这样的东西:

query = "
mutation signInUser($input: AuthProviderEmailInput) {
signInUser(input: $input) {
user {
id
}
token
}
}
"
variables = {
input: {
auth: {
user_id: "example",
password: "example"
}
}
}.to_json
post "serverurl.com", params: { query: query, variables: variables }

最新更新