Home > OS >  How can I test the POST request an external webhook makes to my application?
How can I test the POST request an external webhook makes to my application?

Time:01-31

Folks this is my scenario

There is this external webhook that I would like to test

Is there a way to use VCR or some other tool to record the POST request the webhook makes to my rails app so I can use it in Rspec to run my tests?

The webhook's body is long and very specific that's why I would like to record the request somehow

Is there a way to achieve this?

I tried Requestbin and Charles to record the request but did not manage to make them work so far

CodePudding user response:

Assuming that when you say the problem input is "too long and too specific" what you mean is that it would be inconvenient to construct it inside a test: a simple solution is to put the post body into a separate file.

You can save an example POST body as a file under test/ or spec/ and then read it and post to your app in a request spec:

post(
  my_webhook_path, 
  params: JSON.parse(File.read(path_to_json_file) # assuming the post body is JSON 
  # expect/assert some things about the effects/response of the request
) 

In the docs you will see that you can also add headers, so it should be possible to construct the exact request.

CodePudding user response:

I don't think the VCR is the best tool for that. It's great for recording outgoing requests, not the incoming ones.

I'm guessing you already have a controller and an action that should accept those requests, make sure your app is running and accessible for the service that is going to ping you (ngrok is great for that)

Then in your action do something like

def my_action_accepting_webhook_requests
  puts request_parameters
  puts query_parameters
end

You can just read from the console (or save to file) the params, decide if you want to hardcode it in the spec or save it as a file. And then in your request spec you can re-use it and test your webhook.

  • Related