bernardolins/fake_server

Define routes based on variables from lists

Closed this issue · 2 comments

Hi,
thanks for this nice project, really useful for testing REST clients.

I would like to do the following but it is not working for me. Does anyone have an idea how to make the following code work?

setup do
{:ok, _} = FakeServer.start(:fakeserver)

some_list = ["A", "B", "C", "D", "E"]

for item <- some_list do
FakeServer.put_route(
        :fakeserver,
        "/items/#{item}/details",
        fn(%FakeServer.Request{} = request) ->
          IO.inspect request
          FakeServer.Response.ok!(%{hello: "world"})
        end
      )
end

end

I would like to add routes based on data that is coming from a list, it compiles but the route is never hit by the client. When i hardcode the routes like this it works:

setup do
{:ok, _} = FakeServer.start(:fakeserver)

FakeServer.put_route(
        :fakeserver,
        "/items/A/details",
        fn(%FakeServer.Request{} = request) ->
          IO.inspect request
          FakeServer.Response.ok!(%{hello: "world"})
        end
      )


end

Hi @kuffel, thanks for the feedback!

Can you please add details of the request code? I have the suspect that your requests are going to a server other than the :fakeserver you created on the setup macro.

The following code worked for me:

setup do
    {:ok, _} = FakeServer.start(:fakeserver)

    some_list = ["A", "B", "C", "D", "E"]

    for item <- some_list do
    FakeServer.put_route(
            :fakeserver,
            "/items/#{item}/details",
            fn(%FakeServer.Request{} = request) ->
              IO.inspect request
              FakeServer.Response.ok!(%{hello: "world"})
            end
          )
    end
    :ok
  end

  test "some server" do
    for item <- ["A", "B", "C", "D", "E"] do
      response = HTTPoison.get!("http://127.0.0.1:#{FakeServer.port!(:fakeserver)}/items/#{item}/details")
      assert response.status_code == 200
    end
  end

Thanks for checking it out. You are right i have been using a setup block that returned the full URL.

This was obviously wrong. Thanks for the tip!


  setup do
    {:ok, _} = FakeServer.start(:fakeserver)

    some_list = ["A", "B", "C", "D", "E"]

    for item <- some_list do
      FakeServer.put_route(
        :fakeserver,
        "/items/#{item}/details",
        fn(%FakeServer.Request{} = request) ->
          IO.inspect request
          FakeServer.Response.ok!(%{hello: "world"})
        end
      )
    end

    {:ok,
      %{
        host: "http://localhost:#{FakeServer.port!(:fakeserver)}/"
      }}
  end