This was running without problems, now I'm getting the following error when I use the same ID that I registered in the query:
no implicit conversion of HTTParty::Response into String (TypeError)
Code:
include HTTParty
base_uri 'http://dummy.restapiexample.com/api/v1'
def create
nome = Faker::UniqueGenerator.clear
nome = Faker::Name.unique.first_name
salario = Faker::Number.number(digits: 2)
idade = Faker::Number.number(digits: 2)
$body = {name: nome, salary: salario, age: idade }.to_json
$headers = {
'Accept' => 'application/vnd.tasksmanager.v2',
'Content-Type' => 'application/json'
}
self.class.post('/create', body: $body, headers: $headers)
end
def retrieve(id)
self.class.get("/employee/#{ id }")
When("the request to change the employee is sent") do
$response = @manter_user.create
expect(@manter_user.create.code).to eq (200)
puts $response.body
{"status":"success","data":{"name":"Patrice","salary":59,"age":39,"id":364},"message":"Successfully! Record has been added."}
@id = JSON.parse($response)['id'] #### error
puts @manter_user.retrieve(@id)
no implicit conversion of HTTParty::Response into String (TypeError)
expect(@manter_user.retrieve(@id).code).to eq (200)
end
CodePudding user response:
Since you provided many additional details in your other Post I built a working example for your to review: https://replit.com/@engineersmnky/APIEXAMPLE#main.rb
Just to wrap this up:
Your error is caused by this line
@id = JSON.parse($response)
The $response
variable is an instance of HTTParty::Response
however JSON.parse
is expecting a String
.
To solve this you can use $response.body
which will return a JSON formatted String
for parsing. Additionally HTTParty
will auto parse many known formats so you could skip this step and simply use $response.parsed_response
which will return the same.
Your second issue is that you are trying to access "id" in the wrong location. Your response is formatted as:
resp = {"status":"success",
"data":{
"name":"Patrice",
"salary":59,
"age":39,
"id":364},
"message":"Successfully! Record has been added."}
Here you can see "id" is nested under "data" but you are trying to access it at the top level:
resp["id"]
#=> nil
resp["data"]["id"]
#=> 364
IMPORTANT NOTE: I certainly understand how frustrating being a new programmer can be and how that can impact your attitude and approach, but please try to remember you came to SO for help (and lots of commenters tried to help). If you had taken a minute to listen to the comments, with a clear, calm mind, you would see that they were correct about why your error was occurring and if you had tried to implement their changes you would see everything works exactly as expected. I hope this helps you now and in the future. Best of luck!