Rspec for REST API call - ruby-on-rails-3

Im trying to implement rspec for a http call... But I have not succeeded so far..
http = Net::HTTP.new("secured site url", "443")
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.get("/query params",initheader = {'Accept' =>'application/xml'})
return response
I would need an rspec for this..Though Im new to this, I tried many ways but it says expected: 1 time received: 0 times
Here is all what I have written :
it "should be success" do
#mock_http = mock("http")
#mock_http.should_receive(:new).with("secured site url")
end
Please correct me if Im wrong.. Any help is appreciated! Thanks

Of course you have to activate the method in which the new statement is called so your code should look something like:
it "should be success" do
#mock_http = mock("http")
Net::HTTP.should_receive(:new).with("secured site url", "443")
some_method
end
def some_method
http = Net::HTTP.new("secured site url", "443")
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.get("/query params",initheader = {'Accept' =>'application/xml'})
return response
end

Related

How to test controller methods that use HEAD in Phoenix

Currently the documentation is clear and vibrant with the common HTTP verbs, but we started implementing some HEAD routes today and it is not tested the same way as the others.
To test say a GET method:
conn = get conn, controller_path(conn, :controller_method, params)
So I would assume you would just change get to head, but this is not the case.
Here is my route:
template_journeys_count_path HEAD /v1/templates/:template_id/journeys GondorWeb.V1.JourneyController :count
and my controller method:
def count(conn, %{"template_id" => template_id}) do
count = Templates.get_journey_count(template_id)
conn
|> put_resp_header("x-total-count", count)
|> send_resp(204, "")
end
and my test:
conn = head conn, template_journeys_count_path(conn, :count, template.id)
assert response(conn, 204)
But I am getting an error saying no response received and the resp_header that I added what not in conn.resp_headers
Am I missing something? I also tried to set up a connection build using Plug.ConnTest's method build_conn passing the HEAD method into it but still no luck.
OK after more reading and testing using postman. Phoenix will automatically change HEAD requests into GET requests, there for when phoenix was looking for my route in the router, it was hitting the get route that matched the path with was my :index method.
For HEAD routes:
the verb in the router must be a get, ex: get '/items', :index
if you want to share a path, just add the put_resp_header on your returned connection in the controller method, only the header will be sent in the response
It is ok that the response code is not a 204, as per the w3c doc's HEAD requests can have a 200 response
testing a HEAD request, you can just change a the get to a head and test the response_headers and that no body was sent.
To show my changes... here is my router:
get "/journeys", JourneyController, :index
my controller method:
def index(conn, %{"template_id" => template_id}) do
journeys = Templates.list_journeys(template_id)
conn
|> put_resp_header("x-total-count", "#{Enum.count(journeys)}")
|> render("index.json", journeys: journeys)
end
and my test:
test "gets count", %{conn: conn, template: template} do
conn = head conn, template_journey_path(conn, :index, template.id)
assert conn.resp_body == ""
assert Enum.at(get_resp_header(conn, "x-total-count"), 0) == "1"
end

how to use get method in groovyx.net.http.RESTClient properly

I'm trying to get JSON file via get method in RESTClient.
Right now I'm trying
def url = 'http://urlurlurl'
def username = 'username'
def password = 'password'
def restClient = new RESTClient(url)
restClient.auth.basic(username, password)
render restClient
When I see what I get from restClient, is just prints
'groovyx.net.http.RESTClient#65333e2e'
Which is hard to understand.
Given that the url is a endpoint of a API get method, and contains JSON file, how can I retrieve JSON file so I can parse it and use that JSON file?
Also I'm trying this too
def url = 'http://urlurlurl'
def username = 'username'
def password = 'password'
def restClient = new RESTClient(url)
restClient.auth.basic(username, password)
//Adding get method
def jsonData = restClient.get(/* what value should I put in here?? */)
This gives me a forbbiden error that says:
Error 500: Internal Server Error
URI: JsonRender
Class: groovyx.net.http.HttpResponseException
Message: Forbidden
Any suggestions? Examples that uses get method in RESTClient will be nice.
The url should be the base url for your api. For example if we want to search some data from an api which complete url is http://localhost:9200/user/app/_search. So, we have base url as http://localhost:9200/ and the path to api is user/app/_search. Now the request looks like this
def client = new RESTClient( 'http://localhost:9200/' )
def resp = client.get( path : 'user/app/_search')
log.debug (resp.getContentAsString())
Hope this will work out.
Thanks,

rails post form issue when using https

Following is my code, I am trying to post a form to a https site. I've googled many times with no luck.
post_params = {
name: "Peter",
age: "26",
school: "St. Andrew Secondary"
}
uri = URI.parse('https://www.somehttps.com')
http = Net::HTTP.new(uri, "443")
http.use_ssl = true
http.post_form(uri, post_params)
But I always got:
NoMethodError (undefined method `post_form' for #<Net::HTTP www.somehttps.com:443 open=false>)
Why is it so? Please help me, thank you.
Try - Net::HTTP.post_form(uri, post_params)

getting bad request from ruby on rails ssl post

Looked at: Escaping parameters in set_form_data POST, and Ruby on Rails HTTPS Post Bad Request
def send_request(params)
host = "https://hc.mercurydev.net"
uri = URI.parse(host)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
xml = build_xml_for_checkout(params)
http.start do |http|
req = Net::HTTP::Post.new('http://www.mercurypay.com/InitializePayment')
header = {'Host' => 'hc.mercurydev.net', 'Content-Type' => 'text/xml; charset=utf-8', 'Content-Length' => 'length', 'SOAPAction' => 'http://www.mercurypay.com/InitializePayment'}
req.set_form_data(header, xml)
response = http.request(req)
end
end
This is the first time I have had to build my own post request in ruby, I am sure that I am missing something simple, but what?
-- I have confirmation that the xml is 100% good, so it has to be something in my header or in how I'm building the request.
Edit: After looking at ruby-api-doc: I came up with this:
uri = URI.parse(host)
Net::HTTP.start(uri.hostname, uri.port,
:use_ssl => uri.scheme == 'https').start do |http|
req = Net::HTTP::Post.new uri.path
req.body = xml
req.set_form_data(header)
res = http.request req
end
Which returns (even if I restart my server) that I have an open HTTP session.
So ended up with this:
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Post.new(uri.request_uri)
req.body = xml.to_s
req.initialize_http_header(header)
response = http.request(req)
The key that I was missing was the initialize_http_header() once I got that in there the soap api accepted my submission and then is was just an issue of making sure my syntax was correct.

Posting a gist to github.com in ruby not working

I am trying to create a new gist on github.com by posting the the URL. I have done this in C# and it works fine, but when I try to replicate in ruby on rails the post never seems to work I am always just redirected to the gists/new URL which indicates that the post was not accepted. I figure I am just missing something fundamental in ruby.
require 'net/https'
require 'open-uri'
url = URI.parse('https://gist.github.com/gists')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
req = Net::HTTP::Post.new(url.path)
req.form_data = "file_name[gistfile1]=testclip.txt&description=Test Clip&file_contents[gistfile1]=This is my test clip&login=uname&token=secret"
http.start{|h| h.request(req)}['Location']
I'm out on a limb here, but I'm guessing it has to do with the SSL verify mode. You'll either need to keep from verifying:
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
or give it something to verify against:
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.cert = OpenSSL::X509::Certificate.new(ca_cert)
Take a look at the ca_cert method at Defunkt's Gist gem for more info (you'll need a bundle).