开发者

Passing Custom Headers to Selenium from Capybara

We use custom headers to authenticate our web apps. An http proxy service intercepts requests, confirms the authenticity of the user and then injects custom headers into the request.

In order to test the app, I need to write those headers into the request before it hits my ApplicationController methods. Right now, the current hack works for all my non-javascript tests:

# in hooks.rb
Before do

  require 'capybara/driver/rack_test_driver'
  module Capybara::Driver
    class Authentic < RackTest
      def env
        super.merge('My-Custom-Header' => "foo")
      end
    end
  end

  Capybara.register_driver(:authentic) do |app|
    Capybara::Driver::Authentic.new(app)
  end

  Capybara.default_driver = :authentic
end

#in the controller    
class ApplicationController < ActionController::Base
  before_filter :authenticate

  def authenticate
    render :file => File.join(Rails.root, "public", "403.html") unless request.env.keys.include?('foo')
  end
end

any request I don't want to be authenticated, I can just use a tag to use the regular rack_test driver:

Feature: Authentication
  Valid users should be authenticated.
  Invalid users should be redirected to the login page.

  Scenario: Authorized
    Given I am on the homepage
    Then I should see "Create a New Research Project"

  @rack_test
  Scenario: Unauthorized
    Given I go to the homepage
    Then I should see "You are not authorized to view this page."

when I use the selenium browser, a similar method of redefining env on the driver does not seem to be effective. I assume this is because the app is spooled up in the java thread and all the Rack stuff is already setup.

Where should I inject开发者_开发百科 the custom headers for selenium to pick them up?

Thanks!


you could try and create a new Selenium Driver, a new Profile and overriding the headers on this new profile. I had to do something similar to spoof different user agents.

Capybara.register_driver :mobile_browser do |app|
  require 'selenium-webdriver'

  profile = Selenium::WebDriver::Firefox::Profile.new
  profile['general.useragent.override'] = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7"

  Capybara::Driver::Selenium.new(app, {:browser => :firefox, :profile =>  profile})
end

I'm not sure if you can, though, modify the headers when the steps are running - I'm sure you can, using the Selenium API.


We are using an extra piece of rack middleware (for the test environment) before our application. There you can do anything to the env / request and its completely transparent for the application and all drivers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜