ruby-on-rails – 功能测试移动设备的条件页面内容呈现
我在Rails项目中使用
Mobvious gem来确定用于访问页面的设备类型.我遇到问题的用户故事是:
>移动设备上的用户位于该站点的移动版本上 使用Mobvious实现条件渲染的代码很简单: 应用程序/视图/首页/ index.html.haml - for_device_type :mobile do .switch-to-mobile-site-banner # code for banner 代码本身按预期工作:问题是我想为此写一个RSpec feature test,但我想我似乎无法在RSpec功能测试场景中正确模拟移动用户代理,我无法直接访问请求对象.我的理由是,这里的功能规范比request spec更合适,因为我正在测试页面上是否存在特定内容. 到目前为止,从helper specs of the Mobvious gem获取提示,我已经在我的功能规范中删除了一个请求对象,它将device_type设置为:mobile,我想要,但我似乎无法获得.switch-to-mobile-中的内容要显示的网站横幅: 规格/功能/ mobile_navigation_features_spec.rb feature 'Switch to mobile site banner' do include Mobvious::Rails::Helper given(:env) { double('env') } given(:request) { double('request') } background do allow(env).to receive(:[]).with('mobvious.device_type').and_return(:mobile) allow(request).to receive(:env).and_return(env) end scenario 'mobile user prefers using the desktop site' do visit root_url(desktop: 1) puts "Device type is #{device_type}" # => correctly returns :mobile expect(page).to have_selector('.switch-to-mobile-site-banner') # fails end end 期望是失败的,并使用save_and_open_page来查看页面上的呈现显示没有横幅,我不知道为什么.当代码通过Mobvious’ 我没有专门针对任何实现/测试类型,因此我对如何测试我想要的功能有任何其他想法.我认为 澄清:我正在使用Poltergeist for Capybara的javascript驱动程序. 用解决方案更新 我认为这个问题真正让我感到震惊的是,在mobvious-rails宝石中,当你想获得device_type时,它是calls the 我最终使用Billy Chan和Kaleidoscope的部分答案来制定我喜欢的解决方案更简单,更清洁: 规格/功能/ mobile_navigation_features_spec.rb feature 'Switch to mobile site banner' do background do page.driver.headers = { "User-Agent" => "mobile" } end scenario 'mobile user prefers using the desktop site',js: true do visit root_path(desktop: 1) expect(page).to have_selector('.switch-to-mobile-site-banner') end end 由于Kaleidoscope是第一个提出一系列工作规格的人,我将大部分时间都拿走了,我将给予他赏金,但我会接受Billy Chan的答案是正确的,因为我认为这是一个更”规范的解决方案,我将指导其他人在将来参考. 解决方法
首先,您需要在此功能中打开Javascript,因为移动检测是通过此gem中的Javascript以及许多其他类似解决方案完成的.
feature 'Switch to mobile site banner',js: true do 更新:根据Andrey的评论,Mobivious不使用JS来检测移动设备,因此您不需要启用JS. 其次,我建议你尽可能在集成测试中使用低级模拟.您需要做的是充分表现得像移动用户,看看他会体验到什么.你甚至不需要低水平的Mobvious助手. 我四处搜寻,发现这颗宝石可能有所帮助:https://github.com/mururu/capybara-user_agent 虽然我之前没有使用过那个gem,但语法看起来很简单 feature 'Switch to mobile site banner',js: true do background do set_user_agent(:iphone) end scenario 'mobile user prefers using the desktop site' do visit root_url(desktop: 1) expect(page).to have_selector('.switch-to-mobile-site-banner') end end OP评论的补充答案 >关于到达’example.com’.修复是在访问行中使用root_path而不是root_url.建议您删除对域设置的依赖性. page.driver.headers = {"User-Agent:" => "iphone"} 参考:https://github.com/jonleighton/poltergeist/issues/127 如果这仍然不起作用,您可以在此测试中暂时使用Webkit.毕竟他们都是无头司机.我总是安装这两个宝石,并使用Poltergeist作为主要宝石.安装宝石后,只需将其设置如下. 在测试中 require 'spec_helper' require 'capybara-webkit' feature 'Switch to mobile site banner',js: true do capybara.javascript_driver = :webkit (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |