YEah, I had encounter that during my cucumber test suites, when i wanted to create a custom request, that implied a custom header parameter to be sent.
Puzzling or not, the Watir Webdriver does not do such, plain browser request are sent… so api testing kind of harder to simulate through web browser calls.
BUT! Always is a way
And here’s one:
Instead of doing Browser.goto, to use Ruby Net::Http… can make it. And that can be doable fast, using def methods.
So, here is a comprehensive example of using Ruby and Net::HTTP to POST some JSON with a custom header and looking at the response body:
require 'net/http'
net = Net::HTTP.new("www.myservice.com", 8081)
request = Net::HTTP::Post.new("/some/url/here")
request.set_form_data({"a_named_field" => some_object.to_json})
request.add_field("X-API-KEY", "some api key or custom field")
net.set_debug_output $stdout #useful to see the raw messages going over the wire
net.read_timeout = 10
net.open_timeout = 10
response = net.start do |http|
http.request(request)
end
puts response.code
puts response.read_body
Another approach, based on same approach, using a lib for ease the calls:
Read more here: http://unirest.io/ruby.html – Worth Reading!