16

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?

Community
  • 1
  • 1
user1076132
  • 201
  • 2
  • 8
  • 6
    If you're going to mark a question as a duplicate mightn't it be a good idea to link to the duplicate?! – opsb May 14 '14 at 02:05

3 Answers3

13

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.

czerasz
  • 13,682
  • 9
  • 53
  • 63
Devin M
  • 9,636
  • 2
  • 33
  • 46
3

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
Marek Příhoda
  • 11,108
  • 3
  • 39
  • 53
2

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.

davetapley
  • 17,000
  • 12
  • 60
  • 86