Damian Cardozo Damian Cardozo - 2 years ago 132
Ruby Question

Browser gem testing with capybara

I am using the gem Browser
to detect mobile devices and redirect them to a different landing on a rails app. The code I'm using is this one :

Rails.configuration.middleware.use Browser::Middleware do
redirect_to mobile_landing_path if browser.device.mobile? || browser.device.ipad? || browser.device.tablet?

Now I need to do a feature test using Rspec and capybara, and I'm a little lost here. Really appreciate the help .

Tests I have right now is using capybara user agent and looks like this: but it seems it stills gets the base landing and not the mobile one

feature 'Visiting the site from an' do
context 'Android device' do
background do

scenario 'I should be redirected to mobile landing' do
visit root_path
expect(page).to have_current_path(mobile_landing_path)

Answer Source

The browser gem middleware will only be run when the HTTP_ACCEPT header is set and matches %r[(text/html|/)] . By default the rack-test driver doesn't set any headers. You can either overwrite the provided driver registration like

Capybara.register_driver :rack_test do |app|
  Capybara::RackTest::Driver.new(app, :headers => { 'HTTP_ACCEPT' => 'text/html' })

or you can create a new driver registration

Capybara.register_driver :rack_test_with_html_accept do |app|
  Capybara::RackTest::Driver.new(app, :headers => { 'HTTP_ACCEPT' => 'text/html' })

and then add driver: :rack_test_with_html_accept metadata to your tests that need that header to be set

feature 'Visiting the site from an', driver: :rack_test_with_html_accept do
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download