Question

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

It says: NoMethodError: undefined method 'base_uri' for HTTParty:Module...

Thanks!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top