如何测试使用rspec进行HTTP POST调用的ruby函数?

时间:2018-11-16 14:27:56

标签: ruby testing rspec

我该如何模拟一个API,使用rspec和不带其他gem的方法向方法提供伪造的凭据(用户名和密码)?

这是我要测试的功能:

require 'rubygems'
require 'http'
require 'json'
require_relative './read_file'

def post_gists(user_name, password, file_name)
    file_as_string = file_to_string(file_name)
    file_name = File.basename(file_name)

    obj = {
      description: "",
      public: true,
      files: {
        file_name.to_sym => {
          content: file_as_string
        }
      }
    }

    response = HTTP.basic_auth(user: user_name, pass: password)
      .headers(accept: "application/json")
      .post('https://api.github.com/gists', json: obj) 

    if response.code == 201
      body_hash = JSON.parse(response.body.to_s)
      message = "The file #{file_name} was uploaded correctly at #{body_hash["html_url"]}"
    elsif response.code == 401
      message = "There was a problem with the credentials of the account"
    else  
      message = "There was a problem uploading the file #{file_name}"
    end

    message
  end

0 个答案:

没有答案