Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to set custom request headers when using Capybara in RSpec request specs?

I'm monkey patching Capybara::Session with a set_headers method that assigns to Capybara::RackTest::Browser's options attribute (which I've changed from an attr_reader to an attr_accessor).

The patches:

class Capybara::RackTest::Browser
  attr_accessor :options
end

class Capybara::Session
  def set_headers(headers)
    if driver.browser.respond_to?(:options=) #because we've monkey patched it above
      options = driver.browser.options
      if options.nil? || options[:headers].nil?
        options ||= {}
        options[:headers] = headers
      else
        options[:headers].merge!(headers)
      end
    else
      raise Capybara::NotSupportedByDriverError
    end
  end
end

In my request spec, I'm doing:

page.set_headers("REMOTE_ADDR" => "1.2.3.4")
visit root_path

This works, but I'm wondering if there's a better way, it seems a bit overkill to just be able to set a custom remote_ip/remote_addr on a request. Any thoughts?

like image 485
Chelsea Avatar asked Aug 15 '11 06:08

Chelsea


People also ask

What is Rspec capybara?

Capybara is a web-based test automation software that simulates scenarios for user stories and automates web application testing for behavior-driven software development. It is written in the Ruby programming language. Capybara.


1 Answers

If you want the headers to be globally set on all requests, you can use something like:

Capybara.register_driver :custom_headers_driver do |app|
  Capybara::RackTest::Driver.new(app, :headers => {'HTTP_FOO' => 'foobar'})
end

See the rack_test_driver_spec.rb in Capybara 1.1.2 and Capybara's issue #320, Setting up HTTP headers.

like image 121
awendt Avatar answered Oct 01 '22 22:10

awendt