How to stub requests on domain or after method? - ruby-on-rails

config.before(:each) do
stub_request(:post, "https://api.3rdpartysmsprovider.com/send.php?body=This%20is%20a%20test%20message&destination=60123456789&dlr='1'&output=json&password=0000000&reference=#{#text.sms_uid}&sender=silver&username=0000000").
to_return(:status => 200, :body => "01", :headers => {})
end
I am currently writing specs for a service class that sends an SMS and creates a log of it in our database. I'm trying to stub this request, however #text.sms_uid is a SecureRandom.urlsafe_base64 random code. Also I'm stubbing in config.before(:each).
Because of that, I can't specify the sms_uid in stub_request as the random sms_uid is generated after the stub is called. This causes the test to fail every time. Is there a way I can stub the request after it generates the code (in other words, after it goes through the specific method) or is there a way to stub all requests going through the domain "https://api.silverstreet.com"?

I see two options:
Stub SecureRandom.urlsafe_base64 to return a known string and use that known string when you stub_request:
config.before(:each) do
known_string = "known-string"
allow(SecureRandom).to receive(:known_string) { known_string }
stub_request(:post, "https://api.3rdpartysmsprovider.com/send.php?body=This%20is%20a%20test%20message&destination=60123456789&dlr='1'&output=json&password=0000000&reference=#{known_string}&sender=silver&username=0000000").
to_return(status: 200, body: "01", headers: {})
end
If SecureRandom.urlsafe_base64 is used in other places in your application, you'll need to stub it only in the specs where this request is generated.
Yes, you can stub any POST to that hostname
stub_request(:post, "api.3rdpartysmsprovider.com").
to_return(status: 200, body: "01", headers: {})
or even any request of any kind to that hostname
stub_request(:any, "api.3rdpartysmsprovider.com").
to_return(status: 200, body: "01", headers: {})
and webmock has a very large number of other ways to match requests.

Related

Mock GoogleAPI request

I am using the google-maps gem.
I am trying to mock/stub api requests unsuccessfully.
module GoogleMap
class Route
attr_accessor :start_location, :end_location
def initialize(start_location, end_location)
#start_location = start_location
#end_location = end_location
end
def driving_duration_in_seconds
route.duration.value
end
def driving_distance_in_meters
route.distance.value
end
def driving_distance_hash
return unless start_location && end_location
{ distance_in_meters: driving_distance_in_meters, duration_in_seconds: driving_duration_in_seconds }
end
private
def coordinates_as_strings(location)
"#{location.latitude},#{location.longitude}"
end
def route
#route ||= Google::Maps.route(coordinates_as_strings(start_location), coordinates_as_strings(end_location))
end
end
end
I need to stub:
WebMock::NetConnectNotAllowedError:
Real HTTP connections are disabled. Unregistered request: GET https://maps.googleapis.com/maps/api/directions/json?destination=37.19687112,116.43791248&key=<apikey>&language=en&origin=2.15362819,-81.63712649 with headers {'Accept'=>'*/*', 'Date'=>'Sat, 12 Feb 2022 21:35:55 GMT', 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'}
You can stub this request with the following snippet:
stub_request(:get, "https://maps.googleapis.com/maps/api/directions/json?destination=37.19687112,116.43791248&key=<apikey>&language=en&origin=2.15362819,-81.63712649").
with(
headers: {
'Accept'=>'*/*',
'Date'=>'Sat, 12 Feb 2022 21:35:55 GMT',
'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'
}).
to_return(status: 200, body: "", headers: {})
If I try a most basic stub I get an error:
stub_request(:any, /maps.googleapis.com/).
to_return(status: 200, body: '', headers: {})
Google::Maps::InvalidResponseException:
unknown error: 783: unexpected token at ''
# .../gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:64:in `rescue in response'
# .../gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:60:in `response'
# .../.rvm/gems/ruby-2.7.2/gems/google-maps-3.0.7/lib/google_maps/api.rb:27:in `query'
I think it is erroring out because I am not passing a key in. But I don't see why I should have to pass in a valid api key into a webmock.
I also would not have my route defined by anything. And in order to test that route can return route.distance.value etc, I would need to mock with something.
For other tests I was successful in mocking instances, but to test this lib that it actually works, I feel like mocking instance methods and not that an api was actually called is a waste of a test. Maybe this is just a waste of time, and I should assume it works because I am using a gem.
But I was expecting something like this:
RSpec.describe GoogleMap do
let(:start_location) { create(:location) }
let(:end_location) { create(:location) }
context 'GoogleMaps::Route.new(start_location, end_location)' do
let(:subject) { GoogleMap::Route.new(start_location, end_location) }
# I have not been successful in stubbing this with the correct regex
# stub_request(:get, "https://maps.googleapis.com/maps/api/directions/json?destination=<lat>,<long>key=<key>&language=en&origin=<lat>,<long>").
# with(
# headers: {
# 'Accept'=>'*/*',
# 'Date'=>'Thu, 10 Feb 2022 21:09:02 GMT',
# 'User-Agent'=>'HTTPClient/1.0 (2.8.3, ruby 2.7.2 (2020-10-01))'
# }).
# to_return(status: 200, body: "", headers: {})
# stub_request(:get, %r{https:\/\/maps\.googleapis\.com\/maps\/api\/directions\/json\?destination=.+,.+&key=.+&language=en&origin=.+,.+}).
# stub_request(:any, /maps.googleapis.com/).
# to_return(status: 200, body: '', headers: {})
xit 'gives driving distance in seconds'
xit 'gives driving duration in meters'
end
end
Your WebMock is working fine. Google::Maps::InvalidResponseException is raised after WebMock has replaced the network call. At the point that exception is raised, the Google Maps API client is trying to parse what the network call returned, which is ''.
It's expecting some valid JSON to be returned. If you have your mock return {} is should get past that line. It may well stumble on some other exception later though, as the gem expects a certain schema.
You can dig that out and add in a valid response if you wanted to continue down this path. However, I'd recommend not mocking the network request as that's an implementation detail of a third party piece of code which could change at any time - making your test fail. Instead, I would mock out Google::Maps.route to return what you need it to.

Stub JSON.parse in RSPEC

I'm doing some RSPEC testing here.
If i have this method:
JSON.parse("https://test.com/return_json/reviews.json")
Then I can stub it RSPEC like:
test_reviews = {"reviews" => [{"data1" => "1", "data2"=> "2"}]}
allow(JSON).to receive(:parse).and_return(test_reviews.to_json)
But for this kind (with other method inside (to_uri & read)).
JSON.parse("https://test.com/return_json/reviews.json".to_uri.read)
I tried to used receive_message_chain but no success.
Thanks in advance guys!
You code is not actually calling the url you. You need to make an http call and parse the body. I should probably look like this.
describe :ReviewsController
let(:uri) { URI('https://test.com/return_json/reviews.json') }
let(:reviews) { {"reviews" => [{"data1" => "1", "data2"=> "2"}]} }
before do
stub_request(:get, uri).
with(headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
to_return(status: 200, body: JSON.dump(reviews), headers: {})
end
it 'does whatever you want' do
response = Net::HTTP.get(uri)
expect(JSON.parse(response.body)['data1']).to eq('1') # or whatever you want to test
end
end
It's better explained here.

Stub request when request body is different

Hi I am working on RoR project with ruby-2.5.0 and Rails 5. I am stubbing an http request with stub_request. This http request is basically a mailjet api request to send email.
So, I can not just reuse the snippet, rspec spits out to me, because body differs on every execution.
Stub request
stub_request(:post, "https://api.mailjet.com/v3/send").
with(
body: "{\"FromEmail\":\"abc#abc.ocm\",\"FromName\":\"abc\",\"To\":\"abc#abc.com\",\"Subject\":\"Forgot Password\",\"Text-part\":\"xV3SEtaoa1oyYYfYBt12pw\"}",
headers: {
'Accept'=>'application/json',
'Accept-Encoding'=>'deflate',
'Authorization'=>'Basic YmY0NzdhZmYyMmZlMGQwMzAxNzYzNDNkODUwZTY1MzE6YmRhNmZmYzQ0Y2ZmNGM3MmZkZGNkMjUwODA5YWJhZjM=',
'Content-Length'=>'143',
'Content-Type'=>'application/json',
'Host'=>'api.mailjet.com',
'User-Agent'=>'mailjet-api-v3-ruby/1.5.4'
}).
to_return(status: 200, body: "", headers: {})
Here Text-part is different for each user. I tried hash_including method as follows:-
stub_request(:post, "https://api.mailjet.com/v3/send").
with(
body: hash_including({"FromEmail": "abc#abc.com","FromName": "abc"}),
headers: {
'Accept'=>'application/json',
'Accept-Encoding'=>'deflate',
'Authorization'=>'Basic YmY0NzdhZmYyMmZlMGQwMzAxNzYzNDNkODUwZTY1MzE6YmRhNmZmYzQ0Y2ZmNGM3MmZkZGNkMjUwODA5YWJhZjM=',
'Content-Length'=>'143',
'Content-Type'=>'application/json',
'Host'=>'api.mailjet.com',
'User-Agent'=>'mailjet-api-v3-ruby/1.5.4'
}).
to_return(status: 200, body: "", headers: {})
But when i run test it throws an error:-
JSON::ParserError:
765 : unexpected token at ''
Please help me what is the right syntax to use hash_including method. Thanks in advance.

How to stub HTTP request on Mechanize in Rails?

I have some codebase like this, and I wanna use rspec test favicon_href, but as you like, the favicon_href will call the page function, I know I can mock page function, but for this stage I wanna mock the HTTP request from the given url, so I use WebMock gem's syntax to stub HTTP request, but it seems WebMock is not compatibility with Mechanize, it always show the error in the below despite I relleay have done the stub, anyone know how can solve it or any gem can stub HTTP request on Mechanize?
Code
def favicon_href
#favicon_href ||=
begin
page.at(FAVICON_DOM).attributes['href'].value # finding <link> elements
rescue Exception
'/favicon.ico' # there are some situation the favicon's not <link>'
end
end
def page
#page ||= mechanize.get(url)
end
def mechanize
#mechanize ||= Mechanize.new
end
Error
Failure/Error: #page ||= mechanize.get(valid_url(url))
WebMock::NetConnectNotAllowedError:
Real HTTP connections are disabled. Unregistered request: GET https://tsaohucn.wordpress.com/ with headers {'Accept'=>'*/*', 'Accept-Charset'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Encoding'=>'gzip,deflate,identity', 'Accept-Language'=>'en-us,en;q=0.5', 'Connection'=>'keep-alive', 'Host'=>'tsaohucn.wordpress.com', 'Keep-Alive'=>'300', 'User-Agent'=>'Mechanize/2.7.5 Ruby/2.3.1p112 (http://github.com/sparklemotion/mechanize/)'}
You can stub this request with the following snippet:
stub_request(:get, "https://tsaohucn.wordpress.com/").
with(headers: {'Accept'=>'*/*', 'Accept-Charset'=>'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept-Encoding'=>'gzip,deflate,identity', 'Accept-Language'=>'en-us,en;q=0.5', 'Connection'=>'keep-alive', 'Host'=>'tsaohucn.wordpress.com', 'Keep-Alive'=>'300', 'User-Agent'=>'Mechanize/2.7.5 Ruby/2.3.1p112 (http://github.com/sparklemotion/mechanize/)'}).
to_return(status: 200, body: "", headers: {})
registered request stubs:
stub_request(:get, "https://tsaohucn.wordpress.com/").
with(headers: {'Accept'=>'*/*', 'User-Agent'=>'Ruby'})
stub_request(:any, "http://api.stripe.com/")
stub_request(:any, "/api.stripe.com/")
============================================================
There exists an incompatibility between WebMock and net-http-persistent.
See
https://github.com/bblimke/webmock#connecting-on-nethttpstart
Add
WebMock.allow_net_connect!(:net_http_connect_on_start => true)
to your test set up.

Test oauth2 get_token with rspec

I'm creating a controller spec for the get_token part of an oauth2 authentication. At this point the user has authorized my app and I need to generate and save the token and other information. Rspec fails with a somewhat cryptic error.
Failure/Error: get :auth, { code: "auth_code", scope: "read_write" }
OAuth2::Error:
{:token_type=>"bearer",
:stripe_publishable_key=>"PUBLISHABLE_KEY",
:scope=>"read_write",
:livemode=>"false",
:stripe_user_id=>"USER_ID",
:refresh_token=>"REFRESH_TOKEN",
:access_token=>"ACCESS_TOKEN"}
Here's the controller code. Rspec says it fails on get_token.
require 'oauth2'
def auth
code = params[:code]
client = oauth_client
token_response = client.auth_code.get_token(code, params: { scope: 'read_write' })
token = token_response.token
And here's the test. The webmock should be intercepting get_token. It is the autogenerated webmock suggeted by rspec that I filled in the body with the appropriate request and response body.
before do
stub_request(:post, "https://connect.stripe.com/oauth/token").
with(:body => {"client_id"=>"CLIENT_ID",
"client_secret"=>"SOME_SECRET",
"code"=>"auth_code",
"grant_type"=>"authorization_code",
"params"=>{"scope"=>"read_write"}},
:headers => {'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Content-Type'=>'application/x-www-form-urlencoded',
'User-Agent'=>'Faraday v0.9.0'}).
to_return(:status => 200,
:body => {token_type: "bearer",
stripe_publishable_key: "PUBLISHABLE_KEY",
scope: "read_write",
livemode: "false",
stripe_user_id: "USER_ID",
refresh_token: "REFRESH_TOKEN",
access_token: "ACCESS_TOKEN"},
:headers => {})
end
describe "#auth" do
it "creates a payment gateway" do
get :auth, { code: "auth_code", scope: "read_write"
end
end
This process already works in practice so at least the controller code is not to blame. What am I doing wrong?
After work hard having the same problem I have a solution. Is the header returned in the stub request, you have it blank. The oauth2 gem use the Content-Type to define how to parse the body. Try the stub putting the header in this way:
stub_request(:post, "https://connect.stripe.com/oauth/token").
with(:body => {"client_id"=>"CLIENT_ID",
"client_secret"=>"SOME_SECRET",
"code"=>"auth_code",
"grant_type"=>"authorization_code",
"params"=>{"scope"=>"read_write"}},
:headers => {'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Content-Type'=>'application/x-www-form-urlencoded',
'User-Agent'=>'Faraday v0.9.0'}).
to_return(:status => 200,
:body => {token_type: "bearer",
stripe_publishable_key: "PUBLISHABLE_KEY",
scope: "read_write",
livemode: "false",
stripe_user_id: "USER_ID",
refresh_token: "REFRESH_TOKEN",
access_token: "ACCESS_TOKEN"},
:headers => { 'Content-Type'=> 'application/json;charset=UTF-8'})
I think you're getting this error, because you've stubbed only part of oauth session, i.e. you're trying to send a stale token (or something like that) that has been provided by webmock.
Instead of manual stubbing of these requests, I'd suggest to use special tool: stripe-ruby-mock gem, which has been designed exactly for testing Stripe API.
As an alternative, you may use VCR gem (here are the docs), which allows to write on disk all your http session and play it as it was live. Great tool, highly recommended.

Resources