2017-02-01 50 views
0

該錯誤消息是本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

+1

我會建議直接模仿該服務,而不是嘲笑全局的HTTP調用。我想你會有一個更容易的時間。 '允許(my_service).to接收(:my_method).and_return(my_results)' – steel

+0

@steel嘿感謝您的消息,但是我不完全確定如何利用這個,我寫這個'allow(service).to接收(:get_userinfo_v2).and_return(電子郵件:「[email protected]」,名稱:「petros」)'但我得到未定義的局部變量或方法「服務」哪種有道理? –

+1

是的,這將是更喜歡:'允許(谷歌::蜜蜂:: Oauth2V2 :: Oauth2Service.new)。爲了接收(:get_userinfo_v2).and_return(OpenStruct.new(名稱: 「佩特羅斯」,郵件:「測試@ test.con」))' –

回答

0

編輯:

跟進鋼鐵公司的評論,如果你要使用存根方法,那麼你將需要鏈存根。你可以試試這個:

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: "[email protected]")) 

這使得發生的事情相當明確。

+0

哎'.to_json'清除錯誤,但現在我得到'未定義的方法‘郵件’的零:NilClass'我想這事做與服務,還需要被釘住?我添加了更多的代碼,請參閱'auth_with_oauth2_service' –

+0

是的,我想你的控制器'response'現在是零,它調用'.email'就可以了。 Hmmmmm。我會繼續思考。 –

+0

您可以在成功調用時記錄'response'對象併發布該對象在問題中的內容嗎?謝謝! –