2012-03-09 155 views
0

我有以下簡單的類和方法HTTParty:如何使用RSpec測試此代碼?

class Token 
    require 'httparty' 

    include HTTParty 
    base_uri 'https://<some url>' 
    headers 'auth_user' => 'user' 
    headers 'auth_pass' => 'password' 
    headers 'auth_appkey' => 'app_key' 

    def self.getToken 
    response = get('/auth/token') 
    @token = response['auth']['token'] 
    end 
end 

我知道它的工作原理因爲我可以打電話到Rails控制檯的方法,併成功獲得令牌回來。

如何在RSpec中測試上述代碼?

我在它的初始刺傷不起作用:

describe Token do 
    before do 
    HTTParty.base_uri 'https://<some url>' 
    HTTParty.headers 'auth_user' => 'user' 
    HTTParty.headers 'auth_pass' => 'password' 
    HTTParty.headers 'auth_appkey' => 'app_key' 
    end 

    it "gets a token" do 
    HTTParty.get('auth/authenticate') 
    response['auth']['token'].should_not be_nil 
    end 
end 

它說:NoMethodError: undefined method 'base_uri' for HTTParty:Module ...

謝謝!

+0

你想測試什麼,服務器或這個(非常薄)的客戶端? – 2012-03-09 21:24:54

+0

我想測試客戶端。這只是我爲使用Web服務編寫的第一個方法。我想在添加更多內容之前編寫測試,但不知道要使用的語法。 – 2012-03-09 23:30:29

回答

1

既然你正在測試一個模塊,你可以嘗試這樣的事:

describe Token do 
    before do 
     @a_class = Class.new do 
     include HTTParty 
     base_uri 'https://<some url>' 
     headers 'auth_user' => 'user' 
     headers 'auth_pass' => 'password' 
     headers 'auth_appkey' => 'app_key' 
     end 
    end 

    it "gets a token" do 
     response = @a_class.get('auth/authenticate') 
     response['auth']['token'].should_not be_nil 
    end 
end 

這將創建一個匿名類,並與HTTPparty的類的方法進行了擴展。但是,我不確定響應會如您所願回覆。

+0

我做了一個小小的更正,通過了測試。謝謝你的幫助! – 2012-03-09 23:36:50