2011-12-01 7 views
11

Eventuali duplicati:
Is it possible to specify a user agent in a rails integration test or spec?Come impostare HTTP_USER_AGENT nei test rspec

sto testando una richiesta nel mio rotaie applicazione utilizzando RSpec. Devo essere in grado di impostare l'agente utente prima della richiesta.

questo non sta funzionando:

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 

fine

Come posso specificare correttamente l'user agent?

+5

Se si intende contrassegnare una domanda come duplicata, potrebbe non essere una buona idea collegarsi al duplicato ?! – opsb

risposta

8

Provare a utilizzare questo nel tuo test:

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

o più recente RSpec:

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

Sostituire FeedBurner/1.0 con il programma utente che si desidera utilizzare. Non so se quel codice esatto funzionerà ma something like it should.

+0

Non ho avuto fortuna con questo, anche chiamandolo immediatamente prima di 'post', avevo ancora' request.user_agent == nil' nel controller. Potresti pubblicare un esempio più completo? – dukedave

+0

In Rspec recente, 'request' è nullo. –

3

Questo è quello che faccio in un test di integrazione: si noti l'ultimo hash che imposta REMOTE_ADDR (senza HTTP_). Cioè, non devi impostare l'intestazione HTTP prima della richiesta, puoi farlo come parte della richiesta.

# 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

definire questo da qualche parte (ad esempio 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 

Poi, proprio include DefaultUserAgent quando ne avete bisogno.