質問

次の簡単なクラスと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