开发者

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 se开发者_开发问答ems to not work anymore in Rails 3.

What should I do?


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

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


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


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.


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


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.


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

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

Before making the request


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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜