JSON (JavaScript Object Notation) is a java script object notation that is used by computer to parse and generate data. It is a format that is quite widely used in some API implementation to exchange data. Last week I had to create an automation test to verify the JSON response result from an API. I eventually use 'net/http' gem to send the json request to the server and use json.parse to parse the JSON response data.
You would need to install "net/http" gem and "json" gem to use it. I created a HTTPResponse class to initialize and send the json request to the server.
class HTTPResponse
def self.get url
uri = URI.parse(URI::escape(url))
http = Net::HTTP.new(uri.host,uri.port)
headers={'content-type'=>'applications/json'}
http.get(uri.request_uri, headers)
end
def self.post url, payload
uri = URI.parse(URI::escape(url))
headers={'content-type'=>'applications/json'}
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = payload
Net::HTTP.new(uri.host,uri.port).start{|http| http.request(request)}
end
end
Then in your step definition you can just call the Get and Post method
GET
payload = {
"address" => customer_address,
"cust_id" => customer_id"
}.to_json
url = 'http://www.example.com/web/json/newcust=#{payload}'
@response, @body = HTTPResponse.post(url)
p @response #will return httpok status
p JSON.parse(@body) #will return a hash table which you can parse the value easily
POST
url = 'http://www.example.com/web/json/newcust'
payload = {
"address" => customer_address,
"cust_id" => customer_id"
}.to_json
@response, @body = HTTPResponse.post(url, payload)
p @response #will return httpok status
p JSON.parse(@body) #will return a hash table which you can parse the value easily