2012-03-09 156 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