小编dwa*_*h91的帖子

如何使用 Ruby 和 RSpec 测试 HTTParty API 调用

我正在使用 HTTParty gem 调用 GitHub API 以访问用户的存储库列表。

这是一个使用 Sinatra 的非常简单的应用程序,它根据用户存储库中出现的最常用语言显示用户最喜欢的编程语言。

我对如何编写一个模拟实际 API 调用的 RSpec 期望值有点困惑,而只是检查是否正在返回 json 数据。

我有一个模拟 .json 文件,但不确定如何在我的测试中使用它。

有任何想法吗?

github_api.rb

require 'httparty'

class GithubApi
  attr_reader :username, :data, :languages

  def initialize(username)
    @username = username
    @response = HTTParty.get("https://api.github.com/users/#{@username}/repos")
    @data = JSON.parse(@response.body)
  end
end
Run Code Online (Sandbox Code Playgroud)

github_api_spec.rb

require './app/models/github_api'
require 'spec_helper'

describe GithubApi do
  let(:github_api) { GithubApi.new('mock_user') }

  it "receives a json response" do

  end
end
Run Code Online (Sandbox Code Playgroud)

为清楚起见,其余文件:

结果.rb

require 'httparty'
require_relative 'github_api'

class Results

 def initialize(github_api = Github.new(username))
   @github_api = github_api
   @languages = …
Run Code Online (Sandbox Code Playgroud)

ruby rspec httparty

9
推荐指数
1
解决办法
6358
查看次数

标签 统计

httparty ×1

rspec ×1

ruby ×1