如何在rspec测试中设置HTTP_USER_AGENT

时间:2011-12-01 19:12:22

标签: ruby-on-rails rspec

  

可能重复:
  Is it possible to specify a user agent in a rails integration test or spec?

我正在使用rspec在rails应用中测试请求。我需要能够在请求之前设置用户代理。

这不起作用:

  describe "GET /articles feed for feedburner" do
it "displays article feed if useragent is feedburner" do
  # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
  @articles=[]
  5.times do
    @articles << Factory(:article, :status=>1, :created_at=>3.days.ago)
  end
  request.env['HTTP_USER_AGENT'] = 'feedburner'
  get "/news.xml" 
  response.should be_success
  response.content_type.should eq("application/xml")
  response.should include("item[title='#{@articles.first.title}']")
end

如何正确指定用户代理?

3 个答案:

答案 0 :(得分:11)

在测试中尝试使用它:

request.stub!(:user_agent).and_return('FeedBurner/1.0')

或更新的RSpec:

allow(request).to receive(:user_agent).and_return("FeedBurner/1.0")

FeedBurner/1.0替换为您要使用的用户代理。我不知道确切的代码是否有效,但something like it should

答案 1 :(得分:3)

这是我在集成测试中所做的 - 注意设置REMOTE_ADDR(没有HTTP_)的最后一个哈希。也就是说,您不必在请求之前设置HTTP标头,您可以将其作为请求的一部分。

# Rails integration tests don't have access to the request object (so we can't mock it), hence this hack
it 'correctly updates the last_login_ip attribute' do
  post login_path, { :email => user.email, :password => user.password }, { 'REMOTE_ADDR' => 'some_address' }
  user.reload
  user.last_login_ip.should == 'some_address'
end

答案 2 :(得分:2)

在某处定义此内容(例如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

然后只需include DefaultUserAgent即可。