我有以下简单的类和HTTParty方法:

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...

谢谢!

有帮助吗?

解决方案

既然你正在测试一个模块,你可能会尝试这样的事情:

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的类方法。但是,我不确定响应是否会像您拥有的那样返回。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top