Sha256: 0aebbacef034292364e468a9bffc2418c721bfe8082c59fc9241d5a3aec9cb7e

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

to_inherit = Capybara.const_defined?("RackTest") ? Capybara::RackTest::Driver : Capybara::Driver::RackTest

class Capybara::RackTestJson::Driver < to_inherit
  def body
    MultiJson.decode(source) || {}
  end

  %w[ get delete ].each do |method|
    class_eval %{
      def #{method}(path, params = {}, env = {})
        super(path, params, env_for_rack(env))
      end

      def #{method}!(path, params = {}, env = {})
        handle_error { #{method}(path, params, env) }
      end
    }
  end

  %w[ post put ].each do |method|
    class_eval %{
      def #{method}(path, json, env = {})
        json = MultiJson.encode(json) unless json.is_a?(String)

        request_env = {
          'CONTENT_LENGTH' => json.size,
          'CONTENT_TYPE'   => "application/json; charset=\#{json.encoding.to_s.downcase}", 
          'rack.input'     => StringIO.new(json)
        }.merge(env_for_rack(env))
        
        super(path, {}, request_env)
      end

      def #{method}!(path, json, env = {})
        handle_error { #{method}(path, json, env) }
      end
    }
  end

  protected
  def env_for_rack(env)
    env.inject({}) do |rack_env, (key, value)|
      env_key = key.upcase.gsub('-', '_')
      env_key = "HTTP_" + env_key unless env_key == "CONTENT_TYPE"
      rack_env[env_key] = value

      rack_env
    end
  end

  def handle_error(&block)
    yield
    raise(Capybara::Json::Error, response) if status_code >= 400
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
capybara-json-0.1.2 lib/capybara/rack_test_json/driver.rb
capybara-json-0.1.1 lib/capybara/rack_test_json/driver.rb