Domanda

I have a Lua module I'm writing for making requests to a public API:

-- users.lua

local http     = require("socket.http")
local base_url = 'http://example.com'
local api_key  = "secret"
local users    = {}

function users.info(user_id)
  local request_url = base_url .. '/users/' .. user_id .. "?api_key=" .. api_key
  print("Requesting " .. request_url)
  local response = http.request(request_url)
  print("Response " .. response)
  return response
end

return users

This works, but I'd like to use TDD to finish writing the entire API wrapper.

I have a spec (using the busted framework) which works, but it makes an actual request to the API:

-- spec/users_spec.lua 

package.path = "../?.lua;" .. package.path

describe("Users", function()
  it("should fetch the users info", function()
    local users = require("users")
    local s = spy.on(users, "info")
    users.info("chip0db4")
    assert.spy(users.info).was_called_with("chip0db4")
  end)
end)

How do I mock this out, much like how WebMock works in Ruby, where the actual endpoint is not contacted? The solution doesn't need to be specific to the busted framework, btw.

È stato utile?

Soluzione

After receiving some excellent feedback from https://github.com/TannerRogalsky, as shown here https://gist.github.com/TannerRogalsky/b56bc886811f8f0a9d2a, I decided to write my own mocking library for http requests: https://github.com/chip/webmock. It's in it's very early stages, but it's at least a start. I'd be grateful for contributions to the repo or suggestion on other approaches or Lua modules available.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top