Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock JSONP call in rspec request spec with capybara?

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)

like image 656
luacassus Avatar asked Jun 22 '12 07:06

luacassus


2 Answers

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

like image 106
Andrew Manshin Avatar answered Sep 21 '22 18:09

Andrew Manshin


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
like image 45
oesmith Avatar answered Sep 22 '22 18:09

oesmith