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?
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With