Search code examples
ruby-on-railsrspecjsonpintegration-testingcapybara

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)


Solution

  • 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