Frage

Ich habe die folgende einfache Klasse und HTTParty-Methode:

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

Ich weiß, dass es funktioniert weil ich die Methode in der Rails-Konsole aufrufen und erfolgreich ein Token zurückerhalten kann.

Wie kann ich den obigen Code in RSpec testen?

Mein erster Versuch funktioniert nicht:

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

Es sagt: NoMethodError: undefined method 'base_uri' for HTTParty:Module...

Danke!

War es hilfreich?

Lösung

Da Sie ein Modul testen, könnten Sie Folgendes versuchen:

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

Dadurch wird eine anonyme Klasse erstellt und um erweitert HTTPpartyKlassenmethoden.Ich bin mir jedoch nicht sicher, ob die Antwort so zurückkommen wird, wie Sie sie haben.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top