Webmock和哈希问题

时间:2017-02-01 21:41:11

标签: ruby-on-rails webmock

错误信息是这个

  

WebMock ::响应:: InvalidBody:          必须是以下之一:[Proc,IO,Pathname,String,Array]。给'哈希'

我正在使用以下代码测试google库以获取控制器中的用户信息

stub_request(:get, "https://www.googleapis.com/userinfo/v2/me")
      .to_return(
        body: {email: "test@test.con", name: "Petros"},
        headers: {"Content-Type"=> ["application/json","charset=UTF-8"]}
      )

这是控制器代码

service = auth_with_oauth2_service(calendar_account.get_token)
      response = service.get_userinfo_v2

      calendar_account.user_id = current_user.id
      calendar_account.email = response.email
      calendar_account.name = response.name

auth_with_oauth2_service包含此

def auth_with_oauth2_service(access_token)

    auth_client = AccessToken.new access_token
    service = Google::Apis::Oauth2V2::Oauth2Service.new
    service.client_options.application_name = "****"

    service.authorization = auth_client

    return service
  end

回复内容表格

#<Hurley::Response GET https://www.googleapis.com/userinfo/v2/me == 200 (377 bytes) 647ms>
Success - #<Google::Apis::Oauth2V2::Userinfoplus:0x007ff38df5e820
 @email="****",
 @family_name="Kyriakou",
 @gender="male",
 @given_name="Petros",
 @id="",
 @link="***",
 @locale="en-GB",
 @name="Petros Kyriakou",
 @picture=
  "***",
 @verified_email=true>

服务是google的授权,然后请求我可以使用response.email和response.name访问的用户数据。

然而,由于谷歌宝石获取信息并从中创建一个哈希,我不能对字符串执行任何JSON.parse等。

这是怎么回事?

测试套件:Rspec,capybara,webmock,VCR

2 个答案:

答案 0 :(得分:0)

编辑:

跟进Steel的评论,如果您要使用存根方法,那么您将需要链接存根。你可以尝试一下:

service = Object.new
allow(Google::Apis::Oauth2V2::Oauth2Service).to receive(:new).and_return(service)
allow(service).to receive(:get_userinfo_v2).and_return(OpenStruct.new( name: "Petros", email: "test@test.con" ))

这使得发生的事情相当明确。

答案 1 :(得分:0)

在WebMock中,不接受哈希作为响应正文。如果响应主体为json,则需要将哈希编码为json:

{ email: "test@test.con", name: "Petros" }.to_json
相关问题