如何在 rspec 测试中设置 HTTP_USER_AGENT
我正在使用 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
end
如何正确指定用户代理?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在测试中使用它:
或者对于较新的 RSpec:
将
FeedBurner/1.0
替换为您要使用的用户代理。我不知道确切的代码是否有效,但类似的代码应该有效。Try using this in your test:
or for newer RSpec:
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.这就是我在集成测试中所做的 - 请注意设置 REMOTE_ADDR 的最后一个哈希(不带 HTTP_)。也就是说,您不必在请求之前设置 HTTP 标头,您可以将其作为请求的一部分进行设置。
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.
在某处定义它(例如
spec_helper.rb
):然后在需要时
包含 DefaultUserAgent
即可。Define this somewhere (e.g.
spec_helper.rb
):Then just
include DefaultUserAgent
when you need it.