---
title: Cucumber, Webrat, HTTP auth, and your API
teaser: How to use the `basic_auth` method in Cucumber specs.
tags: web,testing
author: Jason Morrison
published_on: 2010-04-16
---

When you want to authenticate against an <abbr title="Application Programming
Interface">API</abbr> in your application, and you use the standard Rails
integration test methods to call your endpoint, `#basic_auth` won't work:

```ruby
When /^I post to "([^\"]*)" as "(.*)\/(.*)" with the following params:$/ do |path, username, password, table|
  basic_auth(username, password)
  post_params = table.hashes.first
  post path, post_params
end
```

You'll have to specify the HTTP authorization credentials yourself:

```ruby
When /^I post to "([^\"]*)" as "(.*)\/(.*)" with the following params:$/ do |path, username, password, table|
  encoded_login = ["#{username}:#{password}"].pack("m*").gsub(/\n/, '')
  post_params = table.hashes.first
  post path, post_params, { "HTTP_AUTHORIZATION" => "Basic #{encoded_login}" }
end
```

The `encoded_login` bit is nicked from Webrat's implementation of `#basic_auth`
in
[core/session.rb](http://github.com/aslakhellesoy/webrat/blob/master/lib/webrat/core/session.rb).

## Addendum

*Update*: Actually, a cleaner way to do this is to use Webrat's `visit` or
`request_page` methods, which allow you to use `basic_auth`:

```ruby
When /^I post to "([^\"]*)" as "(.*)\/(.*)" with the following params:$/ do |path, username, password, table|
  basic_auth(username, password)
  post_params = table.hashes.first
  visit path, :post, post_params
end
```

# Step up

What's your favorite Cucumber step you've seen lately?

![''](http://images.thoughtbot.com/ui/stepup2thestreets.jpg)
