¿Cómo probar este código con RSpec?

I have the following simple class and HTTParty method:

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

I know it works because I can call the method in the Rails console and successfully get a token back.

How can I test the above code in RSpec?

My initial stab at it doesn't work:

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

Dice así: NoMethodError: undefined method 'base_uri' for HTTParty:Module...

¡Gracias!

preguntado el 09 de marzo de 12 a las 17:03

what do you want to test, the server or this (extremely thin) client? -

I want to test the client. This is just the first method I've written for consuming the web service. I want to write a test for it before adding more, but don't know the syntax to use. -

1 Respuestas

Since you are testing a module you might try something like this:

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

This creates an anonymous class and extends it with HTTPparty's class methods. However, I am not sure the response will return as you have it.

respondido 10 mar '12, 01:03

I made a small correction which got the test to pass. Thanks for your help! - Jim Connors

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.