Mocking request timeout in RSpec - ruby-on-rails

I have a class that makes a request to another service and I want to test error handing around that request.
The code looks like this:
response = RequestObject.post #this triggers a HTTP request
LocalObject.update(foreign_id: response.id, retrieved_at: Time.current )
In my tests I stub the request out and return JSON on success, but I want to test that if that response raises an error that the :foreign_id and :retrieved_at aren't set.
I stub the successful request like this:
allow(RequestObject).to receive(:post).and_return({id: 1,})
What's a good way to mock RequestObject raising a timeout error?
(I'm using the Faraday gem for my requests)

You can use #and_raise to mock an error.
allow(RequestObject).to receive(:post).and_raise(SomeError)
That should allow you to test that code path.
Here's a link to the rspec docs.

Related

API Negatif Scenario with Rest-Assured and Junit

I want to make an API negative test scenario with Rest-Assured Library. I'm creating a get request for a data that doesn't exist. When I print this response to the console, I want to see the text 'not found' Because postman says this is the request body. But my test failed on get method. I am getting that error
io.restassured.internal.http.HttpResponseException: status code: 404, reason phrase: Not Found
Actually I know the status code is 404. But I can not test about it. How can i write that negative scenario
Response response = given().
when().
get("https://restful-booker.herokuapp.com/booking/1001");

How do you print the response in a Grails / Spock test instead of: org.grails.plugins.testing.GrailsMockHttpServletResponse#62c0fcae

I'm writing Spock tests for my Grails backend. I'm quite new to testing in Grails, and I'm trying to view the response to my mock request.
When I write println(response) I see this in the standard output: org.grails.plugins.testing.GrailsMockHttpServletResponse#62c0fcae
instead of the actual response. Is there anyway to view the contents of this mock http response instead of what is currently being printed?
Just use Groovy's dump method:
Generates a detailed dump string of an object showing its class, hashCode and fields.
println(response.dump())
My example:
def response = new GrailsMockHttpServletResponse()
println(response.dump())
Output:
<org.grails.plugins.testing.GrailsMockHttpServletResponse#6a79c292 outputStreamAccessAllowed=true writerAccessAllowed=true characterEncoding=ISO-8859-1 charset=false content= outputStream=org.springframework.mock.web.MockHttpServletResponse$ResponseServletOutputStream#21a947fe writer=null contentLength=0 contentType=null bufferSize=4096 committed=false locale=en_US cookies=[] headers=[:] status=200 errorMessage=null forwardedUrl=null includedUrls=[]>

Any way to debug RSpec request specs?

I am writing a test for a Rails API in RSpec and the endpoint has token authentication set up. I need to pass an Authorization header in the request, but I keep getting a 401 unauthorized error. Is there any way to debug and get some insight into actually which headers are being passed etc. from these types of specs? Otherwise it seems like shooting in the dark. I should note that the token provided below is working perfectly in Postman.
describe "Chirps API" do
it "GET /chirps should return 200" do
get "/chirps", headers: {
"Authorization": "Token token=7cc9f851ea0e4013b7b15ec9131f6d58"
}
expect(response).to have_http_status(200)
end
end
Assuming your controller action is chirps as well, this will help you see the complete request object
def chirps
Rails.logger.info(request.env) # complete request object
Rails.logger.info(request.headers) #just the headers
...
end
To be more interactive you can insert a byebug, then issue the command.
it { byebug }
Then enter your get in the console.

Stubing HTTPS call using WebMock

I'd like to stub https call using webmock.
Let's assume gateway url as https://some_gateway.com.
After doing:
stub_request(:post, 'https://some_gateway.com').with(body: {})
in specs.
I use Net::HTTP to generate request:
Net::HTTP.post_form(URI.parse('https://some_gateway.com'), {})
I receive problem because Webmock expects https://some_gateway.com but receives version with added port 433 so: http://www.secure.fake-payment.com:443/gateway_prod so can't see registered stub.
How can I deal with this behavior ?
Take a look at the answer for this question: WebMock: Rspec - Test Facebook Validation by using JSON response
Your code will do http request with port 443 vs doing really https
Net::HTTP.post_form(URI.parse('https://some_gateway.com'), {})
And here you can find the answer how to do https request using Net::HTTP
Using Net::HTTP.get for an https url

Writing Mock RSpec

I have code in my Ruby on rails project as follows, to get HTTP response from non rails API
app/model/rest_api.rb
require "uri"
require "net/https"
require "net/http"
require "active_support"
class RestApi
# the URL for the Twitter Trends endpoint
#url = 'http://api.twitter.com/1/trends.json'
def self.sampleRes
uri = URI.parse( #url)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
return response
end
end
I have just started learning Ruby on Rails and RSPEC. Can someone please help that how can I write RSpec for HTTP request without actually making request to actual API URL(need some mock)
You can mock out the request part and make expectations about what should be called etc.
mock_req = double("http request")
mock_req.should_receive(:request)
Net::HTTP::Get.should_receive(:new).and_return(mock_req)
Your code could also be simplified to:
open('http://api.twitter.com/1/trends.json').read
You aren't doing any error handling, status checking etc. (maybe this is example code?) but, whatever you expect your request to return you should mock/stub out those expectations.

Resources