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

只谈情不闲聊 提交于 2019-11-26 20:19:28

问题


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?


回答1:


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

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



回答2:


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



回答3:


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




回答4:


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.




回答5:


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

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

Before making the request




回答6:


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.




回答7:


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)


来源:https://stackoverflow.com/questions/4383971/is-it-possible-to-specify-a-user-agent-in-a-rails-integration-test-or-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!