John Bachir
John Bachir

Reputation: 22731

Is it possible to specify a user agent in a rails integration test or spec?

I was doing this before in a rails 2 app in a ActionController::IntegrationTest with

get '/', {}, {:user_agent => "Googlebot"}

but this seems to not work anymore in Rails 3.

What should I do?

Upvotes: 49

Views: 12173

Answers (7)

Noé
Noé

Reputation: 651

If you use request.user_agent in your application, you can write the following code:

get '/', headers: { "HTTP_USER_AGENT" => "Googlebot" }

Upvotes: 51

tddrmllr
tddrmllr

Reputation: 468

I was able to get it working on Rails 5.2.1 using this:

get '/path', headers: { 'HTTP_USER_AGENT' => 'Mozilla/5.0 (blah blah)' }

I looked here for the acceptable keywords to the method.

Upvotes: 13

Michael Baldry
Michael Baldry

Reputation: 2028

For myself, in a controller test in rspec3, I used

request.env["HTTP_USER_AGENT"] = "Hello"

Before making the request

Upvotes: 4

Alex Pretzlav
Alex Pretzlav

Reputation: 15615

None of the above answers worked for me, the following is what finally worked in an rspec controller test:

@request.user_agent = "a MobileDevice/User-Agent"
post :endpoint, param: 2354

Upvotes: 15

Yves Senn
Yves Senn

Reputation: 1996

I fixed this behavior and with Rails 4.0 you will be able to specify actual HTTP Headers like "User-Agent" and "Content-Type" in integration and functional tests. There no longer a need to specify them as CGI variables.

If you are interested you can have a look at the change: https://github.com/rails/rails/pull/9700

Upvotes: 7

davetapley
davetapley

Reputation: 17918

If you have a collection of specs which all require a specific user agent, you may find the following helps to DRY up your specs:

Define this somewhere (e.g. spec_helper.rb):

module DefaultUserAgent

  def post(uri, params = {}, session = {})
    super uri, params, {'HTTP_USER_AGENT' => MY_USER_AGENT}.merge(session)
  end

  def get(uri, params = {}, session = {})
    super uri, params, {'HTTP_USER_AGENT' => MY_USER_AGENT}.merge(session)
  end

end

Then just include DefaultUserAgent when you need it.

Upvotes: 3

zsalzbank
zsalzbank

Reputation: 9857

A user agent is just an http header, so you should be able to use the methods here: http://guides.rubyonrails.org/testing.html#helpers-available-for-integration-tests

And pass in the user agent to the headers (I didn't test this):

headers = {"User-Agent" => "Googlebot"}
request_via_redirect(:get, '/', {}, headers)

Upvotes: 0

Related Questions