Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTTP_USER_AGENT in rspec testing [duplicate]

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

I'm testing a request in my rails app using rspec. I need to be able to set the user agent before the request.

This is not working:

  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

end

How can I properly specify the user agent?

like image 273
user1076132 Avatar asked Dec 01 '11 19:12

user1076132


3 Answers

Try using this in your test:

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

or for newer RSpec:

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

Replace FeedBurner/1.0 with the user agent you want to use. I don't know if that exact code will work but something like it should.

like image 179
Devin M Avatar answered Oct 13 '22 16:10

Devin M


This is what I do in an integration test - notice the last hash that sets REMOTE_ADDR (without HTTP_). That is, you don't have to set HTTP header before the request, you can do so as part of the request.

# 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
like image 37
Marek Příhoda Avatar answered Oct 13 '22 16:10

Marek Příhoda


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.

like image 41
davetapley Avatar answered Oct 13 '22 17:10

davetapley