How to mock JSONP call in rspec request spec with capybara? - ruby-on-rails

I'm working on integration my rails application with Recurly.js.
Before I was making requests to recurly from my server side application, therefore I was able to stub all my integration with excellent VCR gem (https://github.com/myronmarston/vcr) but Recurly.js makes request directly to the service from javascript code using JSONP.
The question is: how to mock these jsonp calls in the integration test?
Currently I'm using rspec + capybara + phantomjs driver (https://github.com/jonleighton/poltergeist)

The only approach I came up with is on-the-fly javascript patching. As far as the Poltergeist gem has a method to execute javascript right in the test browser, you could apply the following patch to turn Recurly.js into the test mode:
# The original 'save' function performs JSONP request to Recurly.
# A token is borrowed during the real API interaction.
page.driver.execute_script("""
Recurly.Subscription.save = function (options) {
Recurly.postResult('/subscription', { token: 'afc58c4895354255a422cc0405a045b0' }, options);
}
""")
Just make a capybara-macros, give a fancy name like 'stub_recurly_js' to it and invoke every time before submitting the Recurly.js forms.
Here is also a link to the original post if you want to dig a little deeper: http://pieoneers.tumblr.com/post/32406386853/test-recurlyjs-in-ruby-using-rspec-capybara-phantomjs

Use puffing-billy. It injects a proxy server between your test browser and the outside world, and allows you to fake responses for specific URLs.
Example:
describe 'my recurly jsonp spec' do
before do
# call proxy.stub to setup a fake response
proxy.stub 'https://api.recurly.com/v2/foo', :jsonp => { :bar => 'baz' }
end
it 'does something with recurly' do
....
end
end

Related

Sending a real JSON post request from RSpec

I would like to have an ability of testing a remote 3d party API for endpoint responses, which is why I would like to write a bunch of local rspec tests and launch them periodically, to see if these endpoints are working as expected with no breaking changes. Since my application is highly dependent on this constantly changing API, I have little choice left but to automate my test.
At the moment I took a regular rspec API test code:
require "rails_helper"
RSpec.describe "Remote request", type: :request do
describe ".send request" do
it ".posts valid data" do
post "http://123.45.67.89/api/endpoint",
params: {
"job_request_id": 123456,
"data": "12345",
"app_secret": "12345",
"options": {
...
}
}
expect(JSON.parse response.body).to include("message" => "success")
expect(response).to have_http_status(200)
end
end
end
The problem with this code is that Rspec is hitting the /api/endpoint url, instead of the full http://123.45.67.89/api/endpoint url. How can I change this behaviour?
RSpec's request specs are meant for testing your own application - by sending real HTTP requests. They are not intended for performing remote HTTP requests (even if it is possible monkey with the configuration to request other hosts than localhost).
Among other things a request spec will hit the API for every example - this will give you problems with rate limiting and throttling.
While you could try using a HTTP library like Net::HTTP, Httparty or Typhoeus in a request spec - what you really should do is rethink your methodology. Its a good idea to isolate the interaction between your application and external collaborators.
One way of doing this is by creating client classes that consume the remote API:
class ExampleAPIClient
include HTTParty
base_url 'example.com'
format :json
def get_some_data
self.class.get('/foo')
end
end
You can then test the remote endpoint by testing the client like a Plain Old Ruby Object:
require 'spec_helper'
RSpec.describe ExampleAPIClient do
let(:client) { described_class.new }
describe "#get_some_data" do
let(:response) { client.get_some_data }
it "should be successful" do
expect(response.success?).to be_truthy
end
end
end
This will have the additional benefit of limiting exposure to change in your application as only a single component (the client) should fail if the remote api changes.
Other components which consume the client can stub out the remote interaction easily by stubbing the client.

Mocking capybara page object - Rails / RSpec

I am working on a web crawler which accesses remote pages by submitting search queries via the remote site's search bar:
class Crawler < PoltergeistDriver
def fetch_listing_page(query)
...
visit 'whatever.com'
fill_in('#seachbar', with: query)
find('#searchbar').native.send_key(:return)
...
end
end
I then use the page object to search for specific text inside the body like so:
class Crawler < PoltergeistDriver
...
def fetch_listing_data
...
page.all('some element', ...)
...
end
...
end
My question is can I mock this page object in my tests? My guess is that VCR / Webmock would not work as the requests are made from the client side (poltergeist in my case).
EDIT:
AS Thomas suggested, I ended up injecting PoltergeistDriver instance as a dependency. This way I can simply create another driver (PuffingBilly) for tests and mock the return of page.body with static html.
You can't use WebMock/VCR for this, but you can use a programmable proxy. PuffingBilly - https://github.com/oesmith/puffing-billy - is one that integrates nicely with capybara and poltergeist.

How catch http data repsponce in test via Capybara

In app we use 3-th part service, what sometimes get broken. We regular testing app by Capybara, Poltergeist. But for tests be more specific in error log I need catch in tests data response from get/post api calls to that 3-th par service. I know about Poltergeist method page.driver.network_traffic but there are no data here, useful for me only response.url and response.status , but also I want somehow get data. Thanks in advance.
Capybara is not suited or designed for API testing, see this blog post http://www.elabs.se/blog/34-capybara-and-testing-apis. There is no access to the get and post requests or responses without hacking the underlying code. Instead, try RackTest. RackTest was created to specifically test APIs: https://github.com/brynary/rack-test.
Edit: with rack-test the homepage documentation is not clear but you can use the Rack::Test::Methods mixin to get the response, see http://www.rubydoc.info/github/brynary/rack-test/Rack/Test/Methods.
For example:
require 'rack/test'
class MyTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
MyApp.new
end
def my_test
get '/'
assert last_response.ok?
assert_equal '<expected_response>', last_response.body
end
end

using VCR with Rspec in feature scenarios

I have a Rails 4 app that uses a custom authentication gem that authenticates users against a third-party API. The app requires authentication for most actions on the site (visitors can do very little).
I am trying to use VCR to record the api request made during authentication for all of the integration tests, but all examples that I can find on SO and the Relish documentation only cover how to do this with Rspec in a 'describe do' spec, as referenced here:
https://www.relishapp.com/vcr/vcr/v/1-6-0/docs/test-frameworks/usage-with-rspec
Since no customers are involved on this project, I am writing integration tests with Rspec and Capybara instead of Cucumber, so my tests are using the 'feature/scenario' format like so:
feature 'posts' do
scenario 'a user can log in' do
# use vcr for api request
sign_in_user # refers to a method that handles the api call to log in a user, which is what I would like VCR to record.
expect(page).to have_content("User signed in successfully")
end
end
Using the command described in the documentation:
use_vcr_cassette
inside of the 'scenario' block, returns an error:
Failure/Error: use_vcr_cassette
undefined local variable or method `use_vcr_cassette' for #<RSpec::ExampleGroups::Posts:0x007fb858369c38>
I followed the documentation to setup VCR in my spec/rails_helper.rb (which is included by the spec/spec_helper.rb)... which basically looks like this:
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'support/vcr_cassettes'
c.hook_into :webmock
end
Obviously added gem 'vcr' to my Gemfile development/test group and it is a thing in console and binding.pry from inside of a test.
Has anyone used VCR inside of a Rspec feature? or have any suggestions on what I might do as a workaround?
Thanks in advance
Solution: Taryn East got me to the solution, but it is slightly different than the link posted for anyone trying to do this moving forward.
here is the most basic config in spec/rails_helper.rb or spec/spec_helper.rb:
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
c.configure_rspec_metadata!
end
using c.configure_rspec_metadata! is required for Rspec to handle the :vcr tag.
And in an Rspec Feature spec:
feature 'users' do
scenario 'logged in users should be able to do stuff', :vcr do
# authenticate user or make other http request here
end
end
Oddly enough, in my tests - VCR is recording the response and if passes the first time, but fails the second time. I traced this to the response being stored differently than it is received.
On a normal request (using excon) like so:
resp = Excon.post(url, :body => data, :headers => { "Content-Type" => "application/x-www-form-urlencoded", "Authorization" => authorization_header })
The response has a header that is accessible in this format:
resp.headers["oauth_token"]
which returns an oauth token.
In the VCR response, it is being stored differently and only accessible as:
resp.headers["Oauth-Token"]
Which is weird, but workable. This may be a bug with VCR or some issue with Excon... too busy to figure that one out right now, but just a heads up in case anyone else uses this setup and gets a passing test with the live http request and a failing test when using the VCR cassette. A quick workaround is to either change the VCR cassette data to match what your code expects, or modify your code to accept either available value.

Fake call to a web service in all cucumber tests

My Rails app makes a call to a web service.
I am using the FakeWeb gem to fake these calls in some tests by registering the URI like this:
FakeWeb.register_uri(:get, "http://webservice.com/param?value=a", :response => fake_response)
How can I set this fake registration for the entire test environment, as opposed to setting it up manually for each test ?
Most likely, putting that in your spec/spec_helper.rb file will do the trick. I haven't used FakeWeb, myself, but that's where you'd put any global initialization.
Take look at VCR rubygem.
It records your test suite's HTTP interactions and replays them during test run.
In a file in spec/support/, make a call to register_uri inside a Before block:
Before do
FakeWeb.register_uri(:get, "http://webservice.com/param?value=a", :response => fake_response)
end
I use this trick to set up mock responses using webmock, and it works like a charm.

Resources