I am working on a Rails project where I have to test the API with Cucumber. I have to test a POST type API and I need to verify its response. I have tried something like:
When(/^I make abc API call$/) do
#url = 'http://example.com/api/abc'
#params = '{
data: {
type: "abc",
attributes: {
title: "example",
all_day: "0",
start_date: "1409175049",
end_date: "1409175049"
}
}
}'
#login_token = 'pHufpGplLTYJnmWh5cqKoA'
end
Then(/^It should return success for abc$/) do
post 'http://example.com/api/abc', body: #params,
headers: { 'Accept' => 'application/json',
'login_token' => #login_token,
'Content-Type' => 'application/json' }
end
But I am not sure how to verify the status code from the response and any attributes from the response. Something like:
Then(/^It should return success for abc$/) do
post 'http://example.com/api/abc', body: #params,
headers: { 'Accept' => 'application/json',
'login_token' => #login_token,
'Content-Type' => 'application/json' }
.to_return(status: 200, body: '{ title: "abc" }')
end
How can I achieve it?
If you are using Capybara this should work for you:
Then /^I should get a response with status (\d+)$/ do |status|
response = post 'http://example.com/api/abc', body: #params,
headers: { 'Accept' => 'application/json',
'login_token' => #login_token,
'Content-Type' => 'application/json' }
response.status_code.should include(status.to_i)
end
Related
I would like test my service with rspec but i got a error in my return body undefined method 'each' for "invoices":String because in my original method i parse an array in the response
I would like know how can i test this method and send a array in return body
My method in service:
def generate_invoices
invoices_ids = []
response = HTTParty.get('https://books.zoho.com/api/v3/invoices?organization_id='\
"#{ENV['ZOHO_ORGANISATION_ID']}&cf_lc_contract_id_startswith=#{#contract_id}&"\
'cf_facture_final=true', headers: { 'Authorization' => "Zoho-oauthtoken #{#access_token}" })
response.code == 200 ? response : raise_error(response.body)
response['invoices'].each do |invoice|
invoices_ids.push invoice['invoice_id']
end
invoices_ids.join(',')
end
stub request i tried:
stub_request(:get, 'https://books.zoho.com/api/v3/invoices?cf_facture_final=true'\
"&cf_lc_contract_id_startswith=123&organization_id=#{ENV['ZOHO_ORGANISATION_ID']}")
.with(headers: { 'Authorization' => 'Zoho-oauthtoken access_token' })
.to_return(status: 200, body: { 'invoices' => [{ "invoice_id": '123' }] }.to_json,
headers: {})
Try this at the end of your call:
.to_return(status: 200, body: '{"invoices" => [{ "invoice_id": "123"}]}', headers: {})
I am working on a rails application to send a post message to a server but each time i tried to send a post request to the sever there seems to be no post data sent to the server. However, if I use postman to send the message with json format the server responds correctly to the post request. I am relatively new to rails and i am not sure if my configuration is wrong. Please I need help. Here is my my code:
def send_information
HTTParty.post("https://example.com/api/json.php",
:body => {
user: 'Nancy Cole',
item: 'mobile phone',
content: 'Hurray the server has received your message',
id: 2,
:headers => {
'Content-Type' => 'application/json' }
}
)
end
I think you have to change your syntax like below :-
response = HTTParty.post("https://example.com/api/json.php",
headers: {
"Content-Type" => "application/json"
},
body: {user: 'Nancy Cole',
item: 'mobile phone',
content: 'Hurray the server has received your message',
id: 2
}.to_json
)
#syntax
response = HTTParty.post(url,
headers: {},
body: {}.to_json
)
I need to stub my HTTP Party request to run my spec and I have to store the transaction Id i get from the parsed_response.Here is my stub
stub_request(:post, {MYURL).to_return(status: 200, body: "{'Success': { 'TransactionId' => '123456789' }}", headers: {})
I get my response to the request as
#<HTTParty::Response:0x5d51240 parsed_response="{'Success': { 'TransactionId' => '123456789' }}", #response=#<Net::HTTPOK 200 readbody=true>, #headers={}>
i need to store transactionid from the field
response.parsed_response['Success']["perfiosTransactionId"]
by i am getting null from there.Can any one help me modify my stub response so that i could get the transactionid saved
PS: If I check the fileds of response i get
response.success? ----> true
response.parsed_response --> "{'Success': { 'TransactionId' => '123456789' }}"
response.parsed_response['Success'] ---> "Success"
You're sending the payload in wrong format:
stub_request(
:post,
{MYURL}
).to_return(
status: 200,
body: '{"Success": { "TransactionId": "123456789" }}', # valid json string
headers: {"Content-Type" => "application/json"}
)
It's must be a valid json object, not a ruby hash.
Here is another way:
stub_request(
:post,
{MYURL}
).to_return(
status: 200,
body: {
"Success": { "TransactionId" => "123456789" }
}.to_json, # valid json string
headers: {"Content-Type" => "application/json"}
)
I have try to making a POST request to google cloud messaging server as follow from my Rails controller using httparty gem
#response = HTTParty.post("https://android.googleapis.com/gcm/notification",
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
)
#json = JSON.parse(#response.body)
render :json => #json
The response I got it not a notification key. It is
{
"error": "BadJsonFormat"
}
What's wrong in my code?
My Rails controller request format is
POST /api/fcm HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: cfd40d1e-81f4-5402-a3cd-f6749f868291
{
"user_id" : "42"
}
I guess httparty gem expects json data
So replace
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
with
:body => {
:text => {
:operation => "remove",
:notification_key_name => "43",
:registration_ids => [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
Try removing to to_json on post. This would work if you were calling it for a Hash, but what it's doing here is double-escaping your string (which is already valid JSON).
If you want to send a minimal JSON request (i.e. without the extra spaces and carriage returns), you can also use
JSON.parse('{
"operation" : "remove",
...
}').to_json
I am trying to implement this javascript code
var token = "<page_access_token>";
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
into ruby on rails code
def reply_back(sender, text)
page_token = "*****"
base_uri = "https://graph.facebook.com/v2.6/me/messages"
messageData = {
text: text
}
qs = {
access_token: page_token
}
json = {
recipient: {
id: sender
},
message: messageData
}
response = RestClient.post base_uri, qs.to_json, json.to_json, :content_type => :json, :accept => :json
p "this is the response #{response}"
end
but obviously i am doing something wrong, i am getting this in console
(wrong number of arguments (4 for 2..3))
on line
response = RestClient.post base_uri, qs.to_json, json.to_json, :content_type => :json, :accept => :json
any insight?
You should put all your params in one params hash like this:
params = {
recipient: { id: sender },
message: { text: text },
access_token: page_token
}
response = RestClient.post base_uri, params.to_json, content_type: 'application/json', accept: 'application/json'
p "this is the response #{response}"
According to documentation, you should merge you params and pass it in method as one object:
params = qs.merge(json)
response = RestClient.post(base_uri,
params.to_json,
content_type: :json, accept: :json)
This method expects 2 or 3 arguments. In this case the third argument is a hash { content_type: :json, accept: :json }. Since it is a last argument, you can omit curly braces.