ruby-on-rails - 用于检测设备的 Rspec
问题描述
这是我的任务
1)新建路由localhost:3000/device
2)考虑如果这个url是从手机或桌面浏览器中点击的,那么
3) 跟踪 URL 被点击的系统/设备(iOS、android、web)
4)根据请求来自的设备,我们需要重定向到其他一些URL(例如,iOS——>“iOS应用商店”,android——>“Android play store”,web——>“google页”)
5) 找出可用于跟踪发出请求的系统的不同方法,什么是最好的实施方法,为什么?
在这里我找到了一个解决方案,但在 rspec 中它会导致错误。
这是我的路线
get :devise, to: 'topics#devise'
这是我的控制器
class TopicsController < ApplicationController
def devise
if request.env['HTTP_USER_AGENT'].downcase.match(/mac/i)
redirect_to 'https://itunes.apple.com/us/app/apple-store/id375380948?mt=8'
elsif request.env['HTTP_USER_AGENT'].downcase.match(/windows/i)
redirect_to 'https://www.microsoft.com/en-in/store/apps/windows'
elsif request.env['HTTP_USER_AGENT'].downcase.match(/android/i)
redirect_to 'https://play.google.com/store?hl=en'
else
redirect_to root_path
end
end
end
当我点击 urllvh.me:3000/devise
时,它会重定向到相应的应用商店。
这是我的控制器规格
context 'devise' do
it 'should detect the device' do
get :devise
response.should redirect_to '/https://www.microsoft.com/en-in/store/apps/windows'
end
end
这导致了错误:
预期响应是重定向到http://test.host/https://www.microsoft.com/en-in/store/apps/windows但重定向到http://test.host/。
预期“ http://test.host/https://www.microsoft.com/en-in/store/apps/windows ”为 === “ http://test.host/ ”。
如果我以错误的方式做,请告诉一些做 rspec 的建议
解决方案
如果您的 rails 版本在控制器中不是太古老,您可以使用request.user_agent
(无论如何它都会查看 env,但这会使代码更清晰)
浏览器在标头中传递用户代理User-agent
(最终在机架环境中),因此您需要在测试中对此进行模拟。
为了测试这一点,我建议使用请求规范而不是控制器规范(在 rails 5 中已弃用):
RSpec.describe 'Topics...', type: :request do
it "redirects for ios" do
get '/your/topcis/path/here', headers: { 'HTTP_USER_AGENT' => 'iPhone' }
expect(response).to redirect_to(/\.apple\.com/)
end
end
(以上使用 rails 5,对于较旧的 rails 标头将只是散列,而不是关键字参数)
你也可以用case
语句编写你的方法:
def devise
redirect_to case request.user_agent.downcase
when /mac/i then 'https://itunes.apple.com/us/app/apple-store/id375380948?mt=8'
when /windows/i then 'https://www.microsoft.com/en-in/store/apps/windows'
when /android/i then 'https://play.google.com/store?hl=en'
else
root_path
end
end
推荐阅读
- python - 使用视觉里程计进行相机轨迹估计
- d3.js - d3 geoPath投影弄乱了地图
- docker - 错误:container_linux.go:235:启动容器进程导致keycloak/keycloak-gatekeeper
- javascript - 我该如何填充
- php - 在单个产品页面上显示 WooCommerce 产品循环页面中自定义库存状态字段的结果
- python - Python静态方法包装器是不必要的吗?
- php - 未找到接口“App\additional\IManage”
- javascript - 具有展开/折叠内容的引导 4 卡片组 - 希望展开的内容仅影响当前卡片
- r - 有雨天在长期平均值的 81-119% 范围内的年数
- apk - 如何在我的 messenger lite 的聊天中添加背景图片?