vendredi 16 novembre 2018

How to test a ruby function which makes a HTTP POST call with rspec?

How can i mock an API, giving fake credentials (username and password) to the method with rspec and with/out any other gem?

Here is the function i want to test:

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

Aucun commentaire:

Enregistrer un commentaire