Remember_me
Remember_me

Reputation: 283

Http testing my ruby based API

I'm trying to test my ruby API, but I m facing some difficulties to send the right data format. I can easily create a desired data format from rspec controller test. And testing passes.

This is the data I expect on my controller :

{
  agreements: [
    {
      agreement_id: 1,
      money_value: 500,
    },
    {
      agreement_id: 2,
      money_value: 1500
    },
  ]
}

And in my controller have this that expects the data in format like this :

def permitted_params
    params.permit(agreements:
      [
        :agreement_id,
        :money_value
    ]).require(:agreements)
end

However when I try to test it with HTTP client, here is how :

data = {:agreements =>[{:agreement_id =>1, :money_value =>500}, {:agreement_id =>2, :money_value =>1500}]}

req = Net::HTTP::Post.new(uri)
req.set_form_data(data)
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req) 
end

I get 400 bad request back. Even though everything looks right, however on the server side when I inspect a request, I get this for params (relevant part):

<ActionController::Parameters {"agreements"=>"{:agreement_id =>2, :money_value=>1500}"

Which tells me two things, first of all it sees agreements as a Hash rather than an array, and also it only sees the last element of that Hash (since it's same key).

What am I doing wrong? Why is my request getting constructed with hash rather than with Array?

Question update:

Here is a error associated with 400 :

param is missing or the value is empty: agreements

Also I m using rails 5.

Upvotes: 1

Views: 63

Answers (1)

BenKoshy
BenKoshy

Reputation: 35731

The data you are sending doesn't seem to match with what you are expecting in your controller.

data = {:agreements =>[{:agreement_id =>1, :money_value =>500}, {:agreement_id =>2, :money_value =>1500}]}

but according to your controller and what you're accepting in params, you need another agreements key inserted in there:

params[:agreements] = {agreements: #<-----------Notice the agreements key here# [
    {
      agreement_id: 1,
      money_value: 500,
    },
    {
      agreement_id: 2,
      money_value: 1500
    }
  ]}

So you'd have to add another :agreements key to the data you are sending and add it also to your test data.

(or alternatively you could change params.) whatever is easier for you.

I hope this helps.

Upvotes: 1

Related Questions