【问题标题】:How to test this code with RSpec?如何使用 RSpec 测试此代码?
【发布时间】:2012-03-09 17:02:56
【问题描述】:

我有以下简单的类和 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...

谢谢!

【问题讨论】:

  • 你想测试什么,服务器还是这个(非常瘦的)客户端?
  • 我想测试客户端。这只是我为使用 Web 服务而编写的第一种方法。我想在添加更多之前为它写一个测试,但不知道要使用的语法。

标签: ruby-on-rails-3 syntax rspec tdd httparty


【解决方案1】:

由于您正在测试一个模块,您可能会尝试这样的事情:

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 的类方法对其进行扩展。但是,我不确定响应是否会像您一样返回。

【讨论】:

  • 我做了一个小修正,使测试通过。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多