該錯誤消息是本Webmock和散列問題
WebMock ::響應:: InvalidBody: 必須是以下之一:[PROC,IO,路徑名,字符串,陣列。給予「哈希」
我使用下面的代碼來測試谷歌圖書館用於獲取用戶信息在我的控制器
stub_request(:get, "https://www.googleapis.com/userinfo/v2/me")
.to_return(
body: {email: "[email protected]", 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>
服務是與谷歌的授權,然後請求,我可以與response.email和response.name訪問用戶數據。
然而,由於谷歌的寶石獲取信息,並創建一個散列出來,我不能做任何JSON.parse等上一個字符串。
這是怎麼回事?
測試套件:Rspec的,水豚,webmock,VCR
我會建議直接模仿該服務,而不是嘲笑全局的HTTP調用。我想你會有一個更容易的時間。 '允許(my_service).to接收(:my_method).and_return(my_results)' – steel
@steel嘿感謝您的消息,但是我不完全確定如何利用這個,我寫這個'allow(service).to接收(:get_userinfo_v2).and_return(電子郵件:「[email protected]」,名稱:「petros」)'但我得到未定義的局部變量或方法「服務」哪種有道理? –
是的,這將是更喜歡:'允許(谷歌::蜜蜂:: Oauth2V2 :: Oauth2Service.new)。爲了接收(:get_userinfo_v2).and_return(OpenStruct.new(名稱: 「佩特羅斯」,郵件:「測試@ test.con」))' –