Search code examples
seleniumrspeccapybara

how to interact with javascript JSON response with rspec and capybara


I'm using rspec and capybara and would like to test a JSON response that I get in response to for example click_button. I understand that I can use :js => true but I would like to parse back the JSON that I get. I see that I can do something like:

get '/your/path', format: 'js'

Is there a way to do something like:

click_button('Save', format: 'js')
::JSON.parse(response)....

?

thx


Solution

  • The aim of browser elumation libraries like Selenium is to approach real browsers and allow emulating behavior of real users. Real users can't read responses to AJAX actions so browser emulation libraries don't give such ability. Also it will be quiet hard for Selenium guys to implement it.

    There are several possibilities that you have:

    • Write this test using one of http client libraries. But you can't really test end-to-end something that involves lots of Javascript and AJAX using this method
    • It's likely that AJAX action changes something in the DOM of your application. You can easily write a check for it using Capybara.
    • But if really want to test your app end-to-end and want to directly check HTTP response to AJAX action you should use a proxy that will record all responses. Then you make a search through those responses. Selenium maintainers advice to use Browsermob proxy to do something like this. Here are Ruby bindings for it that are written by a maintainer of Selenium's Ruby bindings